restful-api-featured-img

A RESTful API is a popular way for exchanging data between web clients and servers due to its simplicity, flexibility, and protocol agnosticism. To ensure that a RESTful API is efficient, scalable, and user-friendly, several important factors must be considered during its design process. In this article, I will provide insight into the best practices and valuable principles for RESTful API.

REST API principles do not depend on a particular application or transport protocol, but in this article I assume HTTP being used as an application layer protocol for REST API; since it is the most widely used model.

Principles for RESTful API

Following are the best practices and valuable principles for RESTful API.

1 HTTP Verbs

To make the API more illustrative and easy to understand, REST architecture adopts HTTP method names such as GET, POST, DELETE, PUT etc, which are the verbs and describe the type of request a client makes to a server. The most commonly used HTTP verbs are,

  • GET: fetches data from the server.
  • POST: creates a data object/resource on the server. 
  • PUT: updates or replaces an existing resource.
  • PATCH: partially updates specific data fields of an existing resource on the server.
  • DELETE: deletes data from the server.

2 Endpoints Nouns 

HTTP endpoints are the locations from where particular resources or objects can be accessed. HTTP endpoints should be nouns, for example, we use HTTP GET /books/{book_id} instead of HTTP GET /getBookDetails.

REST API endpoints are nouns (resources) and methods are verbs (action).

examples,

  • GET /books: Retrieves a information about all books
  • GET /books/{id}: Gets details of a book by its id
  • GET /books/{id}/author: fetches author information of a book

3 Use Plural Nouns

Another best practise or convention for RESTful API is to use plural nouns to clearly represent the resources, for example we use GET /books instead of GET /book to get list of books by an API. It improves the structure and readability and avoid ambiguity.

Using a plural noun for the collection resource helps to follow the principles of REST architecture, where each resource has a unique identifier (URI). Plural noun also indicates that the URI represents a collection of resources rather than a single instance.

4 Versioning 

"Change is the only constant in life." - Heraclitus

As the time passes and requirement grows, REST APIs may under go some important changes, which may break some functionalities for the existing client, it is good practise to use API versions. Versioning allows API evolution without breaking the existing functionalities.

There are several approaches to reflect the API version, such as:

  1. Version in URL: The most common and simple approach to include the version number is adding it in the endpoint URL, such as /v1/books. This approach allows to easily switch between different API versions by changing the version number in the URL.
  2. Version as Query String Parameter: Some implementations represent the API version as a query string parameter, such as /books?version=v1.
  3. Version in HTTP Header: This approach adds the version number in an HTTP header, such as Accept: application/vnd.example.v1+json. This approach is less common.

5 Filtering and Sorting

It is desirable to filter and/or sort data retrieved by the server via REST API, that makes it easier for the clients to handle the large chunk of data. Using query string parameters for filtering and sorting are very common practices, which specifies the condition to match the API result.

Filtering example: we may want to retrieve a list of all mathematics books, like GET /books?type=mathematics. As a result, the server returns only mathematics books.

Sorting example: a client can request all books sorted by date in descending order, such as GET /books?sort=desc

Following are some of the best practices to add filtering and sorting in API,

  1. Parameter names for filtering and sorting should be consistent, predictable and easy to understand, for example GET /books?publishDate=””&authorName=”” etc.
  2. Defining a default sorting and filtering behavior is very helpful as it ensures that the server returns a purposeful response in case no filter parameters are defined.
  3. All possible filtering and sorting parameters should be documented clearly.
  4. API should allow multiple filtering and sorting parameters to provide flexible response data.

6 Pagination

In a large enterprise, data can grow very quickly - retrieving a big chunk of data in one go can be slower, hard to manage at client side and possibly cause some network retrieval issues. A good API implements pagination to return small parts of large data sets.

A common approach (but not limited to) to add pagination in the API response, is to add limit and offset query string parameters, such as  GET /books?offset=30&limit=10. Here API will return records starting from an offset = 30 (of an index) but limited to maximum 10 books.

A Good API also includes total and count fields in the GET response to give a hint about the number of records matching the filtering criteria, like,

200 OK
{
    "Total": 100,
    "Count": 10,
    "Items":
    [
        {
            ..
        },
        {
            ..
        }
        ..
    ]
}

7 Handle Errors

A well structured Restful API returns correct and self-explanatory HTTP status codes and error messages to handle errors. These error codes and messages are quite vital for the clients to understand the status of their requests and debug the issues.

The most common HTTP errors are,

  1. 400 Bad Request: indicates that HTTP request is invalid. There could be various reasons for that for example, missing required data, wrong data format etc.
  2. 401 Unauthorized: The client is not authorized to access the requested resource, due to presenting invalid or missing required credentials.
  3. 403 Forbidden: The client is authenticated, but does not have sufficient permissions to access the resource.
  4. 404 Not Found: The requested resource could not be found on the server.
  5. 500 Internal Server Error: An unexpected error occurred on the server while processing the request. 

8 Use HATEOAS

Hypermedia as the Engine of Application State (HATEOAS) helps clients to dynamically discover and navigate the API by following links including in the server response. HATEOAS provides all the information and actions that a client can perform to work with the API through the links included in the resource returned by the API. This helps to reduce the coupling between client and server, making the API more flexible and adaptable to change.

Suppose you have a resource called "books" and the API supports following HTTP methods: GET (to retrieve a specific book or a list of books), POST (to create a new book), PUT (to update a specific book), and DELETE (to delete a specific book).

A HATEOAS response might include links to related resources that a client can use to navigate the API:

{
  "id": 123,
  "title": "Learning Restful API",
  "links": [
    {
      "rel": "self",
      "href": "/books/123"
    },
    {
      "rel": "update",
      "href": "/books/123",
      "method": "PUT",
      "title": "Update this book"
    },
    {
      "rel": "delete",
      "href": "/books/123",
      "method": "DELETE",
      "title": "Delete this book"
    },
    {
      "rel": "collection",
      "href": "/books",
      "title": "All books"
    }
  ]
}

In this example, the "self" link provides the URL for the specific book resource, and the "update" and "delete" links allow the client to update or delete the book using the HTTP methods specified. The "collection" link provides the URL for the list of all books in the API. This allows clients to navigate the API without needing prior knowledge of the URL structure, making it more flexible and resilient to changes.

9 Security

A secure Rest API is critical to protect confidential and sensitive information. A well protected API ensures three main security principles, i.e. Confidentiality, Integrity and Availability.

Following are some of the key security considerations for RESTful APIs,

  1. Authentication: Users must authenticate themselves to access the API. OAuth, JSON Web Tokens (JWT), or API keys, x509 certificates are some of the most effective ways to implement authentication.
  2. Authorization: The API should grant users access only to the resources they are authorized to access. API can enforce authorization by fine-grained mechanisms such as role-based access control.
  3. SSL/TLS encryption: API implementers must protect the data being exchanged between client and server. An effective ways is to use Secure Transport (SSL/TLS encryption) to prevent eavesdropping and tampering by the Man-in-the-Middle.
  4. Input validation: An attacker can inject malicious code/script in HTTP header, query parameter or in body. API must validate all the input received from clients to prevent attacks such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF).

10 Documentation

A well-documented RESTful API helps the developer to understand it better and use it in an effective way. API should have a clearly written documentation, which describes all available endpoints, methods, supported HTTP headers, Media Type, query string and path parameters etc. It should also include the error code and response messages from the server.

API documentation should also include examples of different HTTP requests and response, so that users can formulate their own request in an easy way or understand the response coming from the server.

An interactive API documentation such as swagger is really helpful, that allows the user to try out the API and see the responses in real-time.

API documentation should also comply with the version of API so that users know what to expect in which version. 

Conclusion

Following best practices for designing REST APIs can improve the overall quality, maintainability, and scalability of your application. Some of the key best practices include using clear and consistent naming conventions, using HTTP verbs, endpoint nouns, and status codes appropriately, keeping API responses consistent, and properly handling errors and exceptions. Additionally, documenting your API thoroughly can help that developers to easily understand and use your API.

Next: I recommend to read more articles containing practical examples of REST APIs.

A RESTful API is a popular way for exchanging data between web clients and servers due to its simplicity, flexibility, and protocol agnosticism. To ensure that a RESTful API is efficient, scalable, and user-friendly, several important factors must be considered during its design process. In this article, I will provide insight into the best practices and valuable principles for RESTful API.

REST API principles do not depend on a particular application or transport protocol, but in this article I assume HTTP being used as an application layer protocol for REST API; since it is the most widely used model.

Principles for RESTful API

Following are the best practices and valuable principles for RESTful API.

1 HTTP Verbs

To make the API more illustrative and easy to understand, REST architecture adopts HTTP method names such as GET, POST, DELETE, PUT etc, which are the verbs and describe the type of request a client makes to a server. The most commonly used HTTP verbs are,

  • GET: fetches data from the server.
  • POST: creates a data object/resource on the server. 
  • PUT: updates or replaces an existing resource.
  • PATCH: partially updates specific data fields of an existing resource on the server.
  • DELETE: deletes data from the server.

2 Endpoints Nouns 

HTTP endpoints are the locations from where particular resources or objects can be accessed. HTTP endpoints should be nouns, for example, we use HTTP GET /books/{book_id} instead of HTTP GET /getBookDetails.

REST API endpoints are nouns (resources) and methods are verbs (action).

examples,

  • GET /books: Retrieves a information about all books
  • GET /books/{id}: Gets details of a book by its id
  • GET /books/{id}/author: fetches author information of a book

3 Use Plural Nouns

Another best practise or convention for RESTful API is to use plural nouns to clearly represent the resources, for example we use GET /books instead of GET /book to get list of books by an API. It improves the structure and readability and avoid ambiguity.

Using a plural noun for the collection resource helps to follow the principles of REST architecture, where each resource has a unique identifier (URI). Plural noun also indicates that the URI represents a collection of resources rather than a single instance.

4 Versioning 

“Change is the only constant in life.” – Heraclitus

As the time passes and requirement grows, REST APIs may under go some important changes, which may break some functionalities for the existing client, it is good practise to use API versions. Versioning allows API evolution without breaking the existing functionalities.

There are several approaches to reflect the API version, such as:

  1. Version in URL: The most common and simple approach to include the version number is adding it in the endpoint URL, such as /v1/books. This approach allows to easily switch between different API versions by changing the version number in the URL.
  2. Version as Query String Parameter: Some implementations represent the API version as a query string parameter, such as /books?version=v1.
  3. Version in HTTP Header: This approach adds the version number in an HTTP header, such as Accept: application/vnd.example.v1+json. This approach is less common.

5 Filtering and Sorting

It is desirable to filter and/or sort data retrieved by the server via REST API, that makes it easier for the clients to handle the large chunk of data. Using query string parameters for filtering and sorting are very common practices, which specifies the condition to match the API result.

Filtering example: we may want to retrieve a list of all mathematics books, like GET /books?type=mathematics. As a result, the server returns only mathematics books.

Sorting example: a client can request all books sorted by date in descending order, such as GET /books?sort=desc

Following are some of the best practices to add filtering and sorting in API,

  1. Parameter names for filtering and sorting should be consistent, predictable and easy to understand, for example GET /books?publishDate=””&authorName=”” etc.
  2. Defining a default sorting and filtering behavior is very helpful as it ensures that the server returns a purposeful response in case no filter parameters are defined.
  3. All possible filtering and sorting parameters should be documented clearly.
  4. API should allow multiple filtering and sorting parameters to provide flexible response data.

6 Pagination

In a large enterprise, data can grow very quickly – retrieving a big chunk of data in one go can be slower, hard to manage at client side and possibly cause some network retrieval issues. A good API implements pagination to return small parts of large data sets.

A common approach (but not limited to) to add pagination in the API response, is to add limit and offset query string parameters, such as  GET /books?offset=30&limit=10. Here API will return records starting from an offset = 30 (of an index) but limited to maximum 10 books.

A Good API also includes total and count fields in the GET response to give a hint about the number of records matching the filtering criteria, like,

200 OK
{
    "Total": 100,
    "Count": 10,
    "Items":
    [
        {
            ..
        },
        {
            ..
        }
        ..
    ]
}

7 Handle Errors

A well structured Restful API returns correct and self-explanatory HTTP status codes and error messages to handle errors. These error codes and messages are quite vital for the clients to understand the status of their requests and debug the issues.

The most common HTTP errors are,

  1. 400 Bad Request: indicates that HTTP request is invalid. There could be various reasons for that for example, missing required data, wrong data format etc.
  2. 401 Unauthorized: The client is not authorized to access the requested resource, due to presenting invalid or missing required credentials.
  3. 403 Forbidden: The client is authenticated, but does not have sufficient permissions to access the resource.
  4. 404 Not Found: The requested resource could not be found on the server.
  5. 500 Internal Server Error: An unexpected error occurred on the server while processing the request. 

8 Use HATEOAS

Hypermedia as the Engine of Application State (HATEOAS) helps clients to dynamically discover and navigate the API by following links including in the server response. HATEOAS provides all the information and actions that a client can perform to work with the API through the links included in the resource returned by the API. This helps to reduce the coupling between client and server, making the API more flexible and adaptable to change.

Suppose you have a resource called “books” and the API supports following HTTP methods: GET (to retrieve a specific book or a list of books), POST (to create a new book), PUT (to update a specific book), and DELETE (to delete a specific book).

A HATEOAS response might include links to related resources that a client can use to navigate the API:

{
  "id": 123,
  "title": "Learning Restful API",
  "links": [
    {
      "rel": "self",
      "href": "/books/123"
    },
    {
      "rel": "update",
      "href": "/books/123",
      "method": "PUT",
      "title": "Update this book"
    },
    {
      "rel": "delete",
      "href": "/books/123",
      "method": "DELETE",
      "title": "Delete this book"
    },
    {
      "rel": "collection",
      "href": "/books",
      "title": "All books"
    }
  ]
}

In this example, the “self” link provides the URL for the specific book resource, and the “update” and “delete” links allow the client to update or delete the book using the HTTP methods specified. The “collection” link provides the URL for the list of all books in the API. This allows clients to navigate the API without needing prior knowledge of the URL structure, making it more flexible and resilient to changes.

9 Security

A secure Rest API is critical to protect confidential and sensitive information. A well protected API ensures three main security principles, i.e. Confidentiality, Integrity and Availability.

Following are some of the key security considerations for RESTful APIs,

  1. Authentication: Users must authenticate themselves to access the API. OAuth, JSON Web Tokens (JWT), or API keys, x509 certificates are some of the most effective ways to implement authentication.
  2. Authorization: The API should grant users access only to the resources they are authorized to access. API can enforce authorization by fine-grained mechanisms such as role-based access control.
  3. SSL/TLS encryption: API implementers must protect the data being exchanged between client and server. An effective ways is to use Secure Transport (SSL/TLS encryption) to prevent eavesdropping and tampering by the Man-in-the-Middle.
  4. Input validation: An attacker can inject malicious code/script in HTTP header, query parameter or in body. API must validate all the input received from clients to prevent attacks such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF).

10 Documentation

A well-documented RESTful API helps the developer to understand it better and use it in an effective way. API should have a clearly written documentation, which describes all available endpoints, methods, supported HTTP headers, Media Type, query string and path parameters etc. It should also include the error code and response messages from the server.

API documentation should also include examples of different HTTP requests and response, so that users can formulate their own request in an easy way or understand the response coming from the server.

An interactive API documentation such as swagger is really helpful, that allows the user to try out the API and see the responses in real-time.

API documentation should also comply with the version of API so that users know what to expect in which version. 

Conclusion

Following best practices for designing REST APIs can improve the overall quality, maintainability, and scalability of your application. Some of the key best practices include using clear and consistent naming conventions, using HTTP verbs, endpoint nouns, and status codes appropriately, keeping API responses consistent, and properly handling errors and exceptions. Additionally, documenting your API thoroughly can help that developers to easily understand and use your API.

Next: I recommend to read more articles containing practical examples of REST APIs.

© 2024 Solution Toolkit . All rights reserved.