REST API Best Practices - Semantics

Consistent, Versioning, Documentation

Posted by Vipin Ragashetti on June 08, 2020 · 3 mins read

Representative State Transfer also known as REST is a resource based architectural style of building APIs. I have been either building the REST APIs and using them for more than 4 years. I feel below are the few points to keep in mind while designing an new API.

  1. Avoid using Verbs, Think about nouns: RESTful APIs are are based on nouns - you will be performing actions on the entities. And these entities we call as resources and they are meant to do something. Consider an example:
  2.   POST /orders
      GET /items
      GET /items/id
      
    versus
      POST /createNewOrders
      GET /getAllItems
      GET /getItemsById/id
      
    The former is more intuitive and follow the common pattern than latter one. Consumers of your endpoints will find it easy to consume the API.
  3. Prevent breaking APIs in Production: Once the API is consumed and published, your API should not change the significant way. If there are any bugs in existing APIs you can fix them as long as it doesn't change your API functionality. If you want to introduce the breaking change, inform your API consumers well in advance and carry out integration tests to confirm everything works correctly with new changes from their side.
  4. Be consistent with APIs: Tie the proper verb with the action on the resource you are performing. For example, use GETs to get the list of items, use POST/PUT to change the value in orders/cart. Also use few proper HTTP status error codes and keep them consistent through your project.
  5. Use Versioning: Businesses are bound to change and the processes change. Version your API when designing the new APIs. There are different ways in which developers version their API accept version in one of the headers, use the version in the URL etc. The best practice is to put the version in the URL like: POST uri/v2/orders
  6. Keep your APIs simple: Keep the response response/ DTO consistent and simple. This will help consumers or other developers consuming your API. Pick one response structure and align to it.
  7. Document your API well: This is one of the most priority item as it would save tons of trouble down the road. This will get less developers asking you the questions all the time.
  8. Filtering and Pagination: In case of GET on resources, introduce filtering and pagination as consumers might be interested with list of items with specific properties. Pagination helps to getting fixed number of records and might be helpful if your number of items is large.

And the list goes on. Designing the REST API is more of a craft than anything else. I feel the above listed are few best practices when designing the REST API.