Guidelines & Best Practices for Design RESTful API

sachinjain007

Sachin Jain

Posted on October 23, 2019

Guidelines & Best Practices for Design RESTful API

Full post found at this Guidelines & Best Practices for Design RESTful API

API development is increasing significantly as they serve the most important use case to build dynamic applications that exchange information. In other words, Restful API is used to connects devices and allow the sharing of data. API exchanges the data between server & client i.e to receive requests from the client and sends a response back.

API Jargons

The term API is an acronym, and it stands for “Application Programming Interface.” API allows applications to exchange data via endpoint to which client sends a request and receives back data. It’s like communication services between two devices.

REST

The term REST is an acronym, and it stands for Representational State Transfer. Rest is an architectural paradigm used in the development of web services. First presented by Roy Fielding

RESTful API

Also, know as a RESTful web service. Web services that conform to the REST architectural style & uses HTTP methods, termed RESTful web services.

In general, API makes the work a lot simpler and easier. It allows the developer to integrate functionality from third-party services rather than building themselves from scratch. As an example, Uber & Ola is using Google Map for a navigation system. This helps them to save time rather than building a navigation system from scratch.

Resful APIGuidelines & Best Practices for Design RESTful API

RESTful API Design

Let’s take an example for Resource type Article, to have a better understanding of designing API’s.

API can be built in any server-side programming language like PHP, Ruby, JS, Java, Python, Go-lang, Elixir. Many popular libraries & frameworks are built to develop Rest API’s like Django, Express, Rails, Spring. These help the developer to speed up the development process.

Let’s start designing restful API by following REST architect.

To GET Record

Bad designs

GET /FetchArticle                   # To fetch all records
GET /getAllArticles/12              # To fetch specific records
  • Do not end up with using verbs or actions to describe the APIs.

Preferred Designs

GET /articles                       # To fetch all records
GET /articles/12                    # To fetch specific records
  • URL of endpoint should contain HTTP methods to describe the functionality of API’s.
  • Use plural or singular nouns but it should be consistent across all the API’s.

To Crete Record

Bad designs

POST /createarticle                 # To create article
GET  /createrecordforartilce        # To fetch all records

Preferred designs

POST /articles                      # To create article records
  • Endpoint URL contains HTTP methods to describe the action of API’s
  • Use plural or singular nouns but it should be consistent across all the API’s.
  • HTTP method for creating records should be POST.

To Update Record

Bad designs

PUT  /updatearticle/id               # To update article
POST /id/modifyarticle               # To update article

Preferred designs

PUT /articles/:id                     # To update article
  • URL of endpoint should contain HTTP methods to describe the action of API’s
  • Use plural or singular nouns but it should be consistent across all the API’s.
  • :id denotes the record by which the record is uniquely identified.

To Delete Record

Bad designs

DELETE /deletearticle/id              # To delete article
POST   /id/removearticle              # To delete article

Preferred designs

DELETE /articles/:id                # To delete article
  • DELETE HTTP method is used to delete record.
  • URL of endpoint should contain HTTP methods to describe the action of API’s
  • Use plural or singular nouns but it should be consistent across all the API’s.
  • :id denotes the record by which the record is uniquely identified.

Documentation

Documentation is an important metric for a developer to use the API. Different API have different behavior which requires different parameters such as HTTPS methods, API response. Developer loves good documentation.

Various good tools are available in the market to help developer to generate the API documents.

  • Swagger: Design and model APIs according to specification-based standards. Improve developer experience with the interactive API documentation.
  • Slate: Slate helps you create beautiful, intelligent, responsive API documentation. Most important Slate is an open-source project and free to use

Security

API security is the important aspects, having a vulnerability in the system opens a way for an attacker to perform malicious activity. Before deployment of restful API. Developer has to identify the vulnerabilities & fix the potential security bugs ASAP otherwise, it threatens the company’s database.

  • Use SSL to secure all your API’s.

  • Use Industry-standard for authentication and authorization like JWT, Oauth2. Authenticate the API, before responding to the request.

  • Don’t store sensitive data in the JWT payload, as it is easy to decode.

  • Use encryption on all sensitive data, do not store the raw password in databases, always encrypt the password before storing it.

  • Rate Limiting to protect against DDoS attacks/brute-force attacks.

    • Return 429 “Too Many Requests” – used to notify that too many requests came quickly from the same origin.
    • Revoke the client credential or blacklist if the client violates the usage of API.
  • Validate all the inputs before responding to a request. Allowing this invalid data into our application could cause unpredictable results.

  • Don’t pass sensitive information in URLs like password, JWT token, API keys as this information stored in browser & server logs.

Versioning

Versioning is important especially when we have third-party clients. It is always good practice to versioning the API as all the latest changes move towards the new version and older changes remain in the previous version. So that the existing app doesn’t get a break by new changes and developers get enough time to reflects these changes into the existing app.

It’s useful to put the version in the URL not mandatory. Versioning can also be achieved with Custom Request Header means the client passes the api-version in header.

URI Versioning

api/v1/articles
api/v2/articles

Characteristics of Good Restful API’s

  • API should do one thing and do it well. And keep it simple
  • Avoid long parameter lists.
  • Use pagination & support sorting by date, numbers of records per page.
  • Proper versioning of the restful API.
  • Readable and intuitive: The interface should exactly do what its name and protocol suggest.
  • Stateless: No method depends on the result of another one.
  • Error handling should be done with HTTP status codes.
  • Proper parameter names, naming conventions, lowercase letters preferred in URI paths. do not abbreviate.
  • Highly available & secure.
  • Version the API, Use pagination, Sorting
  • API’s should be stateless.
  • Good documentation: Developer love good documentation.
  • Hard to exploit. All validation and edge cases should have to cover with proper HTTPS code.
  • KISS [keep it simple silly].

How to scale the API

  • Rate Limiting.
  • Microservice architecture, where each service is designed to execute a specific task well. Breaking down functionality into individual services, which can work in parallel. Multiple instances of services running on multiple machines behind the load balancer.
  • Caching layer, implement Memcache.
  • Use CDN (Content Delivery Network).
  • Use indexing where required.
  • Filtering and pagination.
  • Normalized database and use less SQL joins.

Conclusion

All REST APIs are APIs, but not all APIs are REST APIs. Good designed API is always simple to use & admired by developers.

Following point are only my personal opinion. These are not fixed rules, but only tips from my own years of experience!

Also, see

Ref: ByteNbit A Technology blog - Every Little helps

Thanks for reading. If you have more thoughts please share with me and other readers in comments.

💖 💪 🙅 🚩
sachinjain007
Sachin Jain

Posted on October 23, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related