Eat a RESTful web service

Download Sample Download the sample

Integrating a web service into an application is a common scenario. This article demonstrates how to consume a RESTful web service from a Xamarin.Forms application.

Representational State Transfer (REST) is an architectural style for building web services. Remainder requests are fabricated over HTTP using the same HTTP verbs that spider web browsers use to retrieve spider web pages and to transport information to servers. The verbs are:

  • Go – this performance is used to remember information from the web service.
  • POST – this operation is used to create a new item of data on the web service.
  • PUT – this operation is used to update an particular of data on the web service.
  • PATCH – this performance is used to update an detail of information on the web service by describing a gear up of instructions virtually how the item should be modified. This verb is non used in the sample application.
  • DELETE – this performance is used to delete an detail of information on the web service.

Web service APIs that adhere to Remainder are chosen RESTful APIs, and are defined using:

  • A base URI.
  • HTTP methods, such as GET, Mail service, PUT, PATCH, or DELETE.
  • A media type for the data, such equally JavaScript Object Notation (JSON).

RESTful spider web services typically use JSON messages to return data to the customer. JSON is a text-based information-interchange format that produces compact payloads, which results in reduced bandwidth requirements when sending information. The sample application uses the open up source NewtonSoft JSON.Internet library to serialize and deserialize messages.

The simplicity of REST has helped go far the primary method for accessing web services in mobile applications.

When the sample application is run, it will connect to a locally hosted Balance service, as shown in the following screenshot:

Sample Application

Notation

In iOS nine and greater, App Send Security (ATS) enforces secure connections between cyberspace resources (such every bit the app's back-end server) and the app, thereby preventing accidental disclosure of sensitive information. Since ATS is enabled past default in apps congenital for iOS nine, all connections will be field of study to ATS security requirements. If connections practice non meet these requirements, they will fail with an exception.

ATS tin can exist opted out of if information technology is not possible to apply the HTTPS protocol and secure communication for cyberspace resource. This can be achieved past updating the app'due south Info.plist file. For more than information see App Send Security.

Consume the web service

The REST service is written using ASP.NET Cadre and provides the following operations:

Operation HTTP method Relative URI Parameters
Get a list of to-do items GET /api/todoitems/
Create a new to-do item Post /api/todoitems/ A JSON formatted TodoItem
Update a to-practice item PUT /api/todoitems/ A JSON formatted TodoItem
Delete a to-practise item DELETE /api/todoitems/{id}

The majority of the URIs include the TodoItem ID in the path. For instance, to delete the TodoItem whose ID is 6bb8a868-dba1-4f1a-93b7-24ebce87e243, the client sends a DELETE asking to http://hostname/api/todoitems/6bb8a868-dba1-4f1a-93b7-24ebce87e243. For more information virtually the data model used in the sample application, see Modeling the data.

When the Spider web API framework receives a asking it routes the request to an action. These actions are simply public methods in the TodoItemsController class. The framework utilize routing middleware to friction match the URLs of incoming requests and map them to actions. Balance APIs should use attribute routing the model the app's functionality as a set of resource whose operations are represented by HTTP verbs. Attribute routing uses a set of attributes to map actions directly to route templates. For more data most attribute routing, come across Attribute routing for REST APIs. For more than information nigh edifice the REST service using ASP.NET Core, see Creating Backend Services for Native Mobile Applications.

The HttpClient class is used to transport and receive requests over HTTP. It provides functionality for sending HTTP requests and receiving HTTP responses from a URI identified resource. Each request is sent equally an asynchronous operation. For more than information about asynchronous operations, see Async Support Overview.

The HttpResponseMessage class represents an HTTP response message received from the spider web service after an HTTP request has been made. It contains information nigh the response, including the status code, headers, and any body. The HttpContent form represents the HTTP trunk and content headers, such as Content-Type and Content-Encoding. The content can be read using whatsoever of the ReadAs methods, such as ReadAsStringAsync and ReadAsByteArrayAsync, depending upon the format of the data.

Create the HTTPClient object

The HttpClient instance is declared at the class-level so that the object lives for every bit long as the awarding needs to make HTTP requests, equally shown in the following lawmaking example:

              public class RestService : IRestService {   HttpClient client;   ...    public RestService ()   {     customer = new HttpClient ();     ...   }   ... }                          

Recollect information

The HttpClient.GetAsync method is used to send the GET request to the web service specified past the URI, and then receive the response from the web service, as shown in the post-obit lawmaking example:

              public async Task<List<TodoItem>> RefreshDataAsync () {   ...   Uri uri = new Uri (string.Format (Constants.TodoItemsUrl, string.Empty));   ...   HttpResponseMessage response = await client.GetAsync (uri);   if (response.IsSuccessStatusCode)   {       string content = look response.Content.ReadAsStringAsync ();       Items = JsonSerializer.Deserialize<List<TodoItem>>(content, serializerOptions);   }   ... }                          

The REST service sends an HTTP status code in the HttpResponseMessage.IsSuccessStatusCode property, to indicate whether the HTTP asking succeeded or failed. For this performance the REST service sends HTTP condition lawmaking 200 (OK) in the response, which indicates that the request succeeded and that the requested information is in the response.

If the HTTP operation was successful, the content of the response is read, for display. The HttpResponseMessage.Content belongings represents the content of the HTTP response, and the HttpContent.ReadAsStringAsync method asynchronously writes the HTTP content to a cord. This content is then deserialized from JSON to a List of TodoItem instances.

Alert

Using the ReadAsStringAsync method to retrieve a large response can have a negative performance bear upon. In such circumstances the response should be directly deserialized to avoid having to fully buffer information technology.

Create data

The HttpClient.PostAsync method is used to transport the POST request to the web service specified by the URI, and so to receive the response from the web service, as shown in the following code example:

              public async Task SaveTodoItemAsync (TodoItem detail, bool isNewItem = false) {   Uri uri = new Uri (string.Format (Constants.TodoItemsUrl, string.Empty));    ...   cord json = JsonSerializer.Serialize<TodoItem>(item, serializerOptions);   StringContent content = new StringContent (json, Encoding.UTF8, "application/json");    HttpResponseMessage response = zilch;   if (isNewItem)   {     response = expect customer.PostAsync (uri, content);   }   ...    if (response.IsSuccessStatusCode)   {     Debug.WriteLine (@"\tTodoItem successfully saved.");   }   ... }                          

The TodoItem case is serialized to a JSON payload for sending to the spider web service. This payload is so embedded in the trunk of the HTTP content that will be sent to the spider web service before the request is fabricated with the PostAsync method.

The REST service sends an HTTP status code in the HttpResponseMessage.IsSuccessStatusCode property, to betoken whether the HTTP request succeeded or failed. The mutual responses for this operation are:

  • 201 (CREATED) – the request resulted in a new resources being created before the response was sent.
  • 400 (BAD REQUEST) – the request is non understood by the server.
  • 409 (Disharmonize) – the request could not exist carried out because of a conflict on the server.

Update data

The HttpClient.PutAsync method is used to ship the PUT asking to the web service specified by the URI, and so receive the response from the web service, equally shown in the post-obit lawmaking example:

              public async Task SaveTodoItemAsync (TodoItem item, bool isNewItem = false) {   ...   response = await customer.PutAsync (uri, content);   ... }                          

The operation of the PutAsync method is identical to the PostAsync method that's used for creating information in the web service. All the same, the possible responses sent from the web service differ.

The REST service sends an HTTP status lawmaking in the HttpResponseMessage.IsSuccessStatusCode property, to indicate whether the HTTP request succeeded or failed. The common responses for this operation are:

  • 204 (NO CONTENT) – the request has been successfully processed and the response is intentionally blank.
  • 400 (BAD REQUEST) – the asking is non understood by the server.
  • 404 (NOT Establish) – the requested resource does not exist on the server.

Delete information

The HttpClient.DeleteAsync method is used to transport the DELETE request to the web service specified by the URI, and and then receive the response from the web service, as shown in the following code instance:

              public async Task DeleteTodoItemAsync (string id) {   Uri uri = new Uri (string.Format (Constants.TodoItemsUrl, id));   ...   HttpResponseMessage response = await client.DeleteAsync (uri);   if (response.IsSuccessStatusCode)   {     Debug.WriteLine (@"\tTodoItem successfully deleted.");   }   ... }                          

The REST service sends an HTTP status lawmaking in the HttpResponseMessage.IsSuccessStatusCode property, to indicate whether the HTTP asking succeeded or failed. The mutual responses for this operation are:

  • 204 (NO CONTENT) – the request has been successfully processed and the response is intentionally blank.
  • 400 (BAD REQUEST) – the request is not understood by the server.
  • 404 (NOT FOUND) – the requested resources does not exist on the server.

Local development

If you are developing your REST spider web service locally with a framework such as ASP.Net Core Web API, you tin debug your web service and mobile app at the same time. In this scenario yous must enable clear-text HTTP traffic for the iOS simulator and Android emulator. For information well-nigh configuration your project to permit advice, see Connect to local web services.

  • Microsoft Larn: Consume Balance web services in Xamarin Apps
  • Microsoft Learn: Create a web API with ASP.Net Cadre
  • Creating Backend Services for Native Mobile Applications
  • Aspect routing for REST APIs
  • TodoREST (sample)
  • HttpClient API
  • Android Network Security Configuration
  • iOS App Send Security
  • Connect to local spider web services