8 min read

The application programmable interface (API) is one of the most promising software paradigms to address anything, anytime, anywhere, and any device, which is the one substantial need of the digital world at the moment. This article discusses how APIs and API designs help to address those challenges and bridge the gaps. It discusses a few essential API design guidelines, such as consistency, standardization, re-usability, and accessibility through REST interfaces, which could equip API designers with better thought processes for their API modeling.

This article is an excerpt taken from the book, ‘Hands-On RESTful API Design Patterns and Best Practices‘ written by Harihara Subramanian and Pethura Raj. In this article, you will understand the various design rules of RESTful APIs including the use of Uniform Resource Identifiers, URI authority, Resource modelling and many more.

Goals of RESTful API design

APIs are straightforward, unambiguous, easy to consume, well-structured, and most importantly accessible with well-known and standardized HTTP methods. They are one of the best possible solutions for resolving many digitization challenges out of the box. The following are the basic API design goals:

  • Affordance
  • Loosely coupled
  • Leverage existing web architecture

RESTful API design rules

The best practices and design principles are guidelines that API designers try to incorporate in their API design. So for making the API design RESTFUL, certain rules are followed such as  the following:

  • Use of Uniform Resource Identifiers
  • URI authority
  • Resource modelling
  • Resource archetypes
  • URI path
  • URI query
  • Metadata design rules (HTTP headers and returning error codes) and representations

It will be easier to design and deliver the finest RESTful APIs, if we understand these design rules.

Uniform Resource Identifiers

REST APIs should use Uniform Resource Identifiers (URIs) to represent their resources. Their indications should be clear and straightforward so that they communicate the APIs resources crisp and clearly:

  • A sample of a simple to understand URI is https://xx.yy.zz/sevenwonders/tajmahal/india/agra, as you may observe that the emphasized texts clearly indicates the intention or representation
  • A harder to understand URI is https://xx.yy.zz/books/36048/9780385490627; in this sample, the text after books is very hard for anyone to understand

So having simple, understandable representation in the URI is critical in RESTful API design.

URI formats

The syntax of the generic URI is scheme "://" authority "/" path [ "?" query ] [ "#" fragment ] and following are the rules for API designs:

  • Use forward slash (/) separator
  • Don’t use a trailing forward slash
  • Use hyphens (-)
  • Avoid underscores (_)
  • Prefer all lowercase letters in a URI path
  • Do not include file extensions

REST API URI authority

As we’ve seen different rules for URIs in general, let’s look at the authority (scheme "://" authority "/" path [ "?" query ] [ "#" fragment ]) portion of the REST API URI:

  • Use consistent sub-domain names: As you see in http://api.baseball.restfulapi.org, the API domain should have api as part of its sub-domainConsistent sub-domain names for an API include the following:
    • The top-level domain and the first sub-domain names indicate the service owner and an example could be baseball.restfulapi.org
    • Consistent sub-domain names for a developer portal  include the following:
      • As we saw in the API playgrounds section, the API providers should have exposed sites for APP developers to test their APIs called a developer portal. So, by convention, the developer portal’s sub-domain should have developer in it. An example of a sub-domain with the developer for a developer portal would be http://developer.baseball.restfulapi.org.

Resource modelling

Resource modeling is one of the primary aspects for API designers as it helps to establish the APIs fundamental concepts. In general, the URI path always convey REST resources, and each part of the URI is separated by a forward slash (/) to indicate a unique resource within it model’s hierarchy. Each resource separated by a forward slash indicates an addressable resource, as follows:

Customers, profiles, and APIs are all unique resources in the preceding individual URI models. So, resource modelling is a crucial design aspect before designing URI paths.

Resource archetypes

Each service provided by the API is an archetype, and they indicate the structures and behaviors of REST API designs. Resource modelling should start with a few fundamental resource archetypes, and usually, the REST API is composed of four unique archetypes, as follows:

  • Document
  • Collection
  • Stores
  • Controller

URI path

This section discusses rules relating to the design of meaningful URI paths (scheme "://" authority "/" path [ "?" query ] [ "#" fragment ]) portion of the REST API URIs.

The following are the rules about URI paths:

URI query

These are the rules relating to the design of the query (scheme "://" authority "/" path [ "?" query ] [ "#" fragment ]) portion of the REST API URIs. The query component of the URI also represents the unique identification of the resource, and following are the rules about URI queries:

  • Use the query to filter collections or stores:
    • An example of the limit in the query: https://api.lufthansa.com/v1/operations/flightstatus/arrivals/ZRH/2018-05-21T06:30?limit=40
  • Use the query to paginate collection or store results:
    • An example with the offset in the query: https://api.lufthansa.com/v1/operations/flightstatus/arrivals/ZRH/2018-05-21T06:30?limit=40&offset=10

HTTP interactions

A REST API doesn’t suggest any special transport layer mechanisms, and all it needs is basic Hyper Text Transfer Protocol and its methods to represent its resources over the web. We will touch upon how REST should utilize those basic HTTP methods in the upcoming sections.

Request methods

The client specifies the intended interaction with well-defined semantic HTTP methods, such as GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS. The following are the rules that an API designer should take into account when planning their design:

  • Don’t tunnel to other requests with the GET and POST methods
  • Use the GET method to retrieve a representation of a resource
  • Use the HEAD method to retrieve response headers
  • Use the PUT method to update and insert a stored resource
  • Use the PUT method to update mutable resources
  • Use the POST method to create a new resource in a collection
  • Use the POST method for controller’s execution
  • Use the DELETE method to remove a resource from its parent
  • Use the OPTIONS method to retrieve metadata

Response status codes

HTTP specification defines standard status codes, and REST API can use the same status codes to deliver the results of a client request. The status code categories and a few associated REST API rules are as follows so that the APIs can apply those rules according to the process status:

  • 1xx: Informational: This provides protocol-level information
  • 2xx: Success: Client requests are accepted (successfully), as in the following examples:
    • 200: OK
    • 201: Created
    • 202: Accepted
    • 204: No content
  • 3xx: Redirection: Client requests are redirected by the server to the different endpoints to fulfill the client request:
    • 301: Moved Permanently
    • 302: Found
    • 303: See other
    • 304: Not modified
    • 307: Temporarily redirect
  • 4xx: Client error: Errors at client side:
    • 400: Bad request
    • 401: Unauthorized
    • 403: Forbidden
    • 404: Not found
    • 405: Method not allowed
    • 406: Not acceptable
    • 409: Conflict
    • 412: Precondition failed
    • 415: Unsupported media type
  • 5xx: Server error: These relate to errors at server side:
    • 500: Internal server error

Metadata design

It looks at the rules for metadata designs, including HTTP headers and media types

HTTP headers

HTTP specifications have a set of standard headers, through which a client can get information about a requested resource, and carry the messages that indicate its representations and may serve as directives to control intermediary caches.

The following points suggest a few sets of rules conforming to the HTTP standard headers:

  • Should use content-type
  • Should use content-length
  • Should use last-modified in responses
  • Should use ETag in responses
  • Stores must support conditional PUT request
  • Should use the location to specify the URI of newly created resources (through PUT)
  • Should leverage HTTP cache headers
  • Should use expiration headers with 200 (“OK”) responses
  • May use expiration caching headers with 3xx and 4xx responses
  • Mustn’t use custom HTTP headers

Media types and media type design rules

Media types help to identify the form of the data in a request or response message body, and the content-type header value represents a media type also known as the Multipurpose Internet Mail Extensions (MIME) type.

Media type design influences many aspects of a REST API design, including hypermedia, opaque URIs, and different and descriptive media types so that app developers or clients can rely on the self-descriptive features of the REST API.

The following are the two rules of media type design:

  • Uses application-specific media types
  • Supports media type negotiations in case of multiple representations

Thus we can say that:

  • Support media type selection using a query parameter:
    • To support clients with simple links and debugging, REST APIs should support media type selection through a query parameter named accept, with a value format that mirrors that of the accept HTTP request header
    • An example is REST APIs should prefer a more precise and generic approach as following media type, using the GET https://swapi.co/api/planets/1/?format=json query parameter identification over the other alternatives

Summary

We have briefly discussed the goals of RESTful API design and how API designers need to follow design principles and rules so that you can create better RESTful APIs.

To know more about the rules for most common resource formats, such as JSON and hypermedia, and error types, in brief, client concerns, head over to the book, ‘Hands-On RESTful API Design Patterns and Best Practices‘.

Read Next

Svelte 3 releases with reactivity through language instead of an API
Get to know ASP.NET Core Web API [Tutorial]
Implement an API Design-first approach for building APIs [Tutorial]

A born storyteller turned writer!