Skip to main content

Best practices

RESTful APIs are one of the most common kinds of web services available today. They allow various clients, including browser or mobile apps, to communicate with a server via the RESTful API. Therefore, it is essential to design RESTful API endpoints properly so that we don't run into problems down the road. Below are some practical tips that you can utilize while defining your endpoints.

  • Use nouns instead of verbs in endpoint paths - We should use the nouns for the models that we retrieve or update as the endpoint path. The action should be indicated by the HTTP request method that we’re making. The most common methods include GET, POST, PUT, and DELETE. We should create routes like GET /blogPosts for getting blog posts. Likewise, POST /blogPosts is for adding a new blog post , PUT /blogPosts/{blogId} is for updating the blog post with the given blogId. DELETE /blogPosts/{blogId} is for deleting an existing blog post with the given blogId.
  • Use plural nouns (exception if the resource is a singleton) - Consider a situation your application stores a customer's address and a one-to-one relationship between customer and address exists. In this case, to retrieve the address of a specific customer, you can use the following path /customers/{customerId}/address . Here, we didn't use addresses because it is a singleton in this scenario, where a customer only has one address.
  • Use logical nesting on endpoints - When designing endpoints, it makes sense to group those that contain associated information. If one object can contain another object (sub-model object etc.), you should design the endpoint to reflect that. For example, if we want an endpoint to get the comments for a blog post, we should append the /comments path to the end of the /blogPosts path. We can use the GET method on the path /blogPosts/{blogId}/comments. We get comments on the blog post identified by blogId and then return it in the response. We add comments after the /blogPosts/{blogId} path segment to indicate that it’s a child resource of /blogPosts.