Accessing a REST webservice

In the newest beta release we added a sample for accessing REST webservices.

This sample webservice shows sample access to an information service of Deutsche Bahn (German Railways).

It is a showcase for

  • using an HttpClient to access a REST webservices
  • deserializing JSON results
  • chaining webservice calls
  • synchronizing async calls

There are several points of interest …

Using HttpClient

In the constructor the base address and the headers are customized

client.BaseAddress = new Uri("https://api.deutschebahn.com/freeplan/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));

the call of the service is straightforward …

var response = await client.GetAsync("v1/location/" + name); // build complete URL with params
if (response.IsSuccessStatusCode)
{
     var text = await response.Content.ReadAsStringAsync();                  // read the result (json string)
     return JsonConvert.DeserializeObject<List<RailwayStation>>(text);       // convert to formatted data in classes
}

Deserializing JSON string

The deserialisation of the JSON string is just a single line, but we need a class definition matching the response of the webservice

     return JsonConvert.DeserializeObject<List<RailwayStation>>(text);    

In this sample the name of the class does not matter, but the member names must match the provided names from the webservices

public class RailwayStation
{
    public string Name { get; set; }
    public string Lon { get; set; }
    public string Lat { get; set; }
    public string Id { get; set; }
}

Synchronizing asyc calls

The calls to the HttpClient are alway asynchronous (as provided by .Net Framework).
This has the benefit of a non blocking UI but must be taken into account,
when waiting for a mandatory result.

In the method GetArrivalsForStation we provide a synchronous wrapper that waits until the webservice returns a result.

public string GetArrivalsForStation(string stationname, DateTime date)
{
    Task<string> task = Task.Run<string>(async () => await GetArrivalsForStationAsync(stationname, date));
    return task.Result;
}