Sitemap

REST Best Practices

2 min readJul 18, 2024

--

What is a REST API?

Press enter or click to view image in full size

REST stands for Representational State Transfer. Any API (Application Programming Interface) that follows the REST design principle is said to be RESTful.

Get sunimal malkakulage’s stories in your inbox

Join Medium for free to get updates from this writer.

Best Practices when creating REST API

  • Use JSON for Data Exchange: JSON is preferred over XML for its simplicity and wide support in programming languages.
GET Request:
GET /users/12345 HTTP/1.1
Host: api.example.com
Accept: application/json

Response
{
"id": 12345,
"name": "John Doe",
"email": "johndoe@example.com",
"createdAt": "2024-07-16T12:34:56Z",
"roles": ["admin", "user"]
}
POST Request
POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
"name": "Jane Doe",
"email": "janedoe@example.com",
"password": "securepassword123"
}

Response
{
"id": 67890,
"name": "Jane Doe",
"email": "janedoe@example.com",
"createdAt": "2024-07-16T12:45:00Z",
"roles": ["user"]
}
  • Use Nouns for Endpoints: Endpoints should use nouns instead of verbs, letting HTTP methods (GET, POST, PUT, DELETE) handle actions.
Instead of:
/getUsers
/createPost
/deleteProduct

Use:
/users
/posts
/products
  • Plural Nouns for Collections: Use plural nouns for endpoint collections to indicate multiple resources (e.g., /posts instead of /post).
/users  (collection of user resources)
/posts (collection of post resources)
/comments (collection of comment resources)
  • Use Status Codes for Error Handling: Employ standard HTTP status codes to communicate the result of API requests clearly.
STATUS CODE                          RANGE MEANING
100 – 199 Informational Responses.
For example, 102 indicates the resource is being processed
300 – 399 Redirects
For example, 301 means Moved permanently
400 – 499 Client-side errors
400 means bad request and 404 means resource not found
500 – 599 Server-side errors
For example, 500 means an internal server error
  • Nesting Endpoints to Show Relationships: Nest endpoints to reflect resource relationships, but avoid deep nesting to maintain readability.
  • Filtering, Sorting, and Pagination: Implement these features to manage large datasets efficiently and reduce server load.
https://loollablk.com/posts?tags=react
  • Use SSL for Security: Secure APIs with SSL to protect data and ensure privacy.
https://loollablk.com/posts  - SSL
http://loollablk.com/posts - non SSL
  • Clear Versioning: Use versioning (e.g., /v1/, /v2/) to allow clients to use different versions without breaking functionality.
https://loollablk.com/v1/ 
https://loollablk.com/v2
  • Accurate API Documentation: Provide comprehensive documentation with endpoint details, example requests, and error messages to help users.

--

--

sunimal malkakulage
sunimal malkakulage

Written by sunimal malkakulage

Traveler | Hiker | Coder | Xylophile | 🗻🥾🌇🌌🌄🪐🌓🚴🏽‍♂️🌅🗾🇯🇵 🇱🇰