The most common RESTful API best-practices
Tags: webdev, api, rest
Published: 2022-05-07 14:10:28

#Description#
There are a lot of guides describing the best practices for API Restful design. This is a short collection and summary of some of the most common rules you will find around the web.
   
#The Rules#
1. Sending and receiving data
 - Use JSON for all communication
 - Your API is stateless
 - Allow filtering, sorting and pagination
 - Use the proper HTTP Method
 - The response should be predictable

2. Naming Conventions
 - Use Nouns instead of verbs in endpoints
 - Name Collections with Plural nouns
 - Use Resource nesting
3. Return Error details in the response body
4. Security
 - USE SSL/TLS
 - Secure your API
5. Document your API

##1. Sending and receiving data##
###1.1 Use JSON for all communication###
Using JSON for all communication makes your API predictable. It also makes it easier for other systems to build error handling or exceptions. If you suddenly return an HTML error page your users might find unexpected results and need to spend additional development time.

###1.2 Your API is Stateless###
This means that every request is treated as a new request. Your API should not store any details about the client for future requests. The API won't store the user credentials, tokens or other information carried in the header/body.

###1.3 Allow filtering, sorting and pagination###
A database can grow very large, especially if you have CMS like behaviour inside your API. Use common keywords and default limitations to keeps your database queries fast and efficient.

Commonly used keywords to use in your filters:
```
Limit (default=20) = Max returned items
Offset = Items to skip, allows for pagination
Sort = Sort/order the list by property value
Filter = Allows for searching by property name
```

###1.4 Use the proper HTTP Method###
There are multiple types of HTTP Methods you can use to define your API endpoint. This also allows some endpoints to be reused but with a different HTTP Method. For example you can have 2 `api/cars` endpoints. One for a `GET` and one for a `POST`. Use this to your advantage.

POST   CREATE  = 201, OR 404 IF :ID NOT FOUND, OR 409 IF ID ALREADY EXISTS
GET    READ  = 200, OR 404 IF :ID NOT FOUND
PUT    UPDATE/REPLACE  200, OR 404 IF :ID NOT FOUND
PATCH  UPDATE/MODIFY 200, OR 404 IF :ID NOT FOUND
DELETE DELETE 200, OR 404 IF :ID NOT FOUND


###1.5 The response should be predictable###
Everything in the API should be consistent. If a user sends JSON to an endpoint called `/products` it should return a JSON. Maybe even with an error message. You should in turn never return an error in HTML or return a PDF file if it isn't expected.

##2. Naming Conventions##
###2.1 Name Collections with Plural nouns###
If you allow multiple items to create a collection  you should use plurals in the naming convention. 
Don't use
`GET: /post/`
Do use
`GET: /posts/`

###2.2 Use Nouns instead of verbs in endpoints###
Don't use
`POST: /posts/createNewPost/`
Do use
`POST: /posts/`

###2.3 Use logical nesting###
Don't use
`GET: /posts/comments/:id/`
Do use
`GET: /posts/:id/comments`

##3. Error handling##
###3.1 Return error descriptions in the body###
If something goes wrong, such as validation you might want to inform your user what went wrong.
```
{
    "ResponseStatus": {
         "ErrorCode": "MissingRequiredField",
         "Message": "Property 'Message' is missing"
    }
}
```

##4. Security##
###4.1 Secure your API###
Some users might not have permission to access your API. Think ahead of time and write down who should and shouldn't be able to access your data. Maybe some users have read-access but not delete-access. A common method is using Token Based Authentication 

##5. Document your API##
It should be easy for other developers to use your API. Using automated documentation like SWAGGER helps both you and your users to keep a good overview of the endpoints. Also consider writing documentation on how users can authenticate or query your endpoints. 

#Summary#
Following these steps should make your API predictable and suitable in production environments. You might not be able to apply these rules in all applications you build. Most best practice guides give examples as if there is a CMS behind them and come up with easy examples for GET and POST endpoints. But real life applications might do something more advanced such as calculations or modify the input and output. 

Happy coding!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sra2y6wk0i8pvqxdr4iz.gif)