Structuring your REST APIs the correct way!

Structuring your REST APIs the correct way!

More than half of the industry is writing wrong REST APIs! Anyone is writing any kind of APIs and terms it REST!

The basics of REST API -

  • The endpoints should be based on Resources (Entities) living in your system. Each resource instance could be fetched through a unique path/endpoint known as a URI (for example fetching Book1 - /books/1)
  • The APIs should use request method as the "action" you want to have in your applications - POST for create, GET for list/fetch, PUT for replace, PATCH for in-place update and DELETE for deleting (even soft deletes)
  • Your APIs should be stateless, as in so session / context should be maintained "in the request layer". You can keep context in your data as a state management feature, such as User's state cab be enabled/disabled, but keeping it as a request session is wrong.
  • Data should be cacheable
  • Requests should be well structured, automatically telling the client what went wrong if the resource is ill - structured (400 Bad Requests)

While there are multiple things to see in REST, the basics are that your endpoint is always resource oriented, and your request method is always action oriented.

For example

  • POST /addNewUser -- ❌
  • POST /users -- ✅

Endpoints should be based on resources / entities

  • GET /markOrderComplete -- ❌
  • PUT /order/{orderId} -- ✅

Actions should be based on Request Method, not endpoint

Structuring your APIs

Another thing to keep in mind is the way you structure your resources using Inheritance.

Let's say you have multiple resources/entities in the system - Products, Users, Orders

  • /products -- Work on Products (POST is create and GET is list)
  • /products/{productId} -- Work on Product with given ID (GET is fetch, PUT is replace, PATCH is update, DELETE is delete)
  • /products/{productId}/orders -- Work on all order for given Product ID
  • /orders/{orderId}/products -- Work on products for given Order ID
  • /orders -- Work on all orders in the system
  • /users/{userId}/orders -- Work on orders for given User ID

These are few basics which should be very important in designing APIs as there are many people who want to understand how is the system built as well as maintained given multiple Entities and Actions.

If you like this post, do subscribe to my newsletter here, and give this article a ❤️.

Taksh Chanana

JavaScript Developer | React.js | Next.js | Node.js | Express.js | TypeScript | AWS

1y

Btw, how do you know approx 50% of engineers are wrong in writing APIs?

To view or add a comment, sign in

More articles by Shrey Batra

Insights from the community

Others also viewed

Explore topics