RESTful services - izznogooood/dotnet-wiki GitHub Wiki

Representational State Transfer (REST) is a software architecture style consisting of guidelines and best practices for creating scalable web services. REST is a coordinated set of constraints applied to the design of components in a distributed hypermedia system that can lead to a more performant and maintainable architecture.

A web API that obeys the REST constraints is informally described as RESTful. RESTful web APIs are typically loosely based on HTTP methods to access resources via URL-encoded parameters and the use of JSON or XML to transmit data.

Design principles

Resources

REST APIs are designed around resources, which are any kind of object, data, or service that can be accessed by the client. Resources could be customers, orders, products, etc.

A resource has an identifier, which is a URI that uniquely identifies that resource. For example, the URI for a particular customer might be:

https://e-shop.com/customers/1

Noun plural form is typically used for resource identifiers.

Methods

The HTTP protocol defines a number of methods that assign semantic meaning to a request. The common HTTP methods used by most RESTful web APIs are:

  • GET retrieves a representation of the resource at the specified URI. The body of the response message contains the details of the requested resource.
  • POST creates a new resource at the specified URI. The body of the request message provides the details of the new resource. Note that POST can also be used to trigger operations that don’t actually create resources.
  • PUT either creates or replaces the resource at the specified URI. The body of the request message specifies the resource to be created or updated.
  • PATCH performs a partial update of a resource. The request body specifies the set of changes to apply to the resource.
  • DELETE removes the resource at the specified URI.

The effect of a specific request should depend on whether the resource is a collection or an individual item. The following table summarizes the common conventions adopted by most RESTful implementations

Resource POST GET PUT DELETE
/customers Create new customer Retrieve all customers Bulk update of customers Remove all customers
/customers/1 Error Retrieve the details for customer 1 Update the details of customer 1 if it exists Remove customer 1
/customers/1/orders Create a new order for customer 1 Retrieve all orders for customer 1 Bulk update of orders for customer 1 Remove all orders for customer 1

Status codes

When an operation completes a status code is returned to the client, along with the result (if any). The following should be used as a basis:

  • GET

    A successful GET method typically returns HTTP status code 200 (OK). If the resource cannot be found, the method should return 404 (Not Found).

  • POST

    If a POST method creates a new resource, it returns HTTP status code 201 (Created). The URI of the new resource is included in the Location header of the response. The response body contains a representation of the resource.

    If the method does some processing but does not create a new resource, the method can return HTTP status code 200 and include the result of the operation in the response body. Alternatively, if there is no result to return, the method can return HTTP status code 204 (No Content) with no response body.

    If the client puts invalid data into the request, the server should return HTTP status code 400 (Bad Request). The response body can contain additional information about the error or a link to a URI that provides more details.

  • PUT

    If a PUT method creates a new resource, it returns HTTP status code 201 (Created), as with a POST method. If the method updates an existing resource, it returns either 200 (OK) or 204 (No Content). In some cases, it might not be possible to update an existing resource. In that case, consider returning HTTP status code 409 (Conflict).

  • PATCH

    A successful PATCH method typically returns HTTP status code 200 (OK).

  • DELETE methods

    If the delete operation is successful, the web server should respond with HTTP status code 204, indicating that the process has been successfully handled, but that the response body contains no further information. If the resource doesn’t exist, the web server can return HTTP 404 (Not Found).

Miscellaneous

  • Created conventions

    When a resource is created (POST / PUT) HTTP status code 201 (Created) is returned, in addition a header Location should be set to the URI of the new resource.

    The response body should contains a representation of the new resource.

  • Media types

    Clients and servers exchange representations of resources. For example, in a POST request, the request body contains a representation of the resource to create. In a GET request, the response body contains a representation of the fetched resource.

    The Content-Type header in a request or response specifies the format of the representation. If the server doesn’t support the media type, it should return HTTP status code 415 (Unsupported Media Type).

    A client request can include an Accept header that contains a list of media types the client will accept from the server in the response message. If the server cannot match any of the media type(s) listed, it should return HTTP status code 406 (Not Acceptable).

    RESTful APIs typically support JSON format (application/json):

    {
        "id": 1,
        "name": "Freia AS",
        "organizationNo": "918646485",
        "dateOfFoundation" : "1977-08-15"
    }
    
  • Model validation

    ASP.NET Core provides several built-in attributes for model validation see the section on built-in attributes.

    Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field. Model validation occurs after model binding and reports errors where data doesn't conform to business rules.

    In the sample below a Title with less than 1 character or more than 50 will cause an automatic validation and set the ModelState.IsValid to false, causing the controller to respond with a HTTP 400 response containing error details.

    public class Book
    {
        public int BookId { get; set; }
        [Required]
        [StringLength(50, MinimumLength = 1)]
        public string Title { get; set; }
        public Author Author { get; set; }
    }
    
    

Useful resources

Creating a RESTful API using EF and ASP.NET Core

All communication from the app to the database will go through a RESTful API. Follow this tutorial to create a simple web API using ASP.NET Core.