Restful API Best Practices

Source: Internet
Author: User
Tags ticket

Web APIs has become a very important topic in the last year. We at M-way Solutions is working every day with different backend systems and therefore we know about the importance of a Clean API design.

Typically we use a RESTful design for our web APIs. The concept of REST is to separate the APIs structure into logical resources. There is used the HTTP methods GET, DELETE, POST and PUT to operate with the resources.

These is best practices to design a clean RESTful API:

1. Use nouns but no verbs

For a easy understanding with this structure for every resource:

Resource GET
Read
POST
Create
PUT
Update
DELETE
/cars Returns a list of cars Create a new ticket Bulk Update of cars Delete All Cars
/cars/711 Returns a specific car Method not allowed (405) Updates a specific ticket Deletes a specific ticket

Do not use verbs:

/getallcars/createnewcar/deleteallredcars
2. GET method and query parameters should not alter the state

Use PUT, POST and DELETE methods instead of the GET method to alter the state.
Do is use the GET for state changes:

Get/users/711?activate orget/users/711/activate

3. Use plural nouns

Don't mix up singular and plural nouns. Keep it simple and use only plural nouns for all resources.

/cars instead of/car/users instead of/user/products instead of/product/settings instead of/setting

4. Use Sub-resources for Relations

If A resource is related to another resource use subresources.

Get/cars/711/drivers/returns a list of drivers for car 711GET/CARS/711/DRIVERS/4 Returns driver #4 for car 711

5. Use the HTTP headers for serialization formats

Both, client and server, need to know which format was used for the communication. The format has been specified in the Http-header.

Content-type defines the request format.
Accept defines a list of acceptable response formats.

6. Use HATEOAS

HYpermedia as The Engine oF application sTate is a Principle that hypertext links should is used to create a better navigation through the API.

{  "id": 711,  "Manufacturer": "BMW",  "model": "X5",  "seats": 5,  "Drivers": [   {    "id": "All",    "name": "Stefan jauker",    "links": [     {     "rel": "Self",     "href": "/API/V1/DRIVERS/23"    }   ]  } ]}

7. Provide filtering, sorting, field selection and paging for collections

Filtering:

Use a unique query parameter for all fields or a query language for filtering.

get/cars?color=red Returns A list of red carsget/cars?seats<=2 Returns a list of cars with a maximum of 2 seats

Sorting:

Allow ascending and descending sorting through multiple fields.

Get/cars?sort=-manufactorer,+model

This returns a list of cars sorted by descending manufacturers and ascending models.

Field selection

Mobile clients display just a few attributes in a list. They don ' t need all attributes of a resource. Give the API consumer the ability to choose returned fields. This would also reduce the network traffic and speed up the usage of the API.

Get/cars?fields=manufacturer,model,id,color

Paging

Use limit and offset. It is flexible for the user and common in leading databases. The default should be limit=20 and offset=0

Get/cars?offset=10&limit=5

To send the total entries back to the user with the custom HTTP Header:x-total-count.

Links to the next or previous page should is provided in the HTTP header of link as well. It is important to follow this link header values instead of constructing your own URLs.

Link: 

8. Version your API

Make the API Version mandatory and does not release an unversioned API. Use a simple ordinal number and avoid dot notation such as 2.5.

We is using the URL for the API versioning starting with the letter "V"

/blog/api/v1

9. Handle Errors with HTTP status codes

It is the hard-to-work with a API that ignores error handling. Pure returning of a HTTP with a stacktrace are not very helpful.

Use HTTP Status Codes

The HTTP standard provides through status codes to describe the return values. We don ' t need them all, but there should is used at least a mount of 10.

200–ok–eyerything is working
201–ok–new Resource has been created
204–ok–the Resource was successfully deleted

304–not modified–the Client can use cached data

400–bad request–the Request is invalid or cannot be served. The exact error should is explained in the error payload. e.g. "The JSON is not valid"
401–unauthorized–the request requires an user authentication
403–forbidden–the server understood the request, but was refusing it or the access is not allowed.
404–not Found–there is no resource behind the URI.
422–unprocessable entity–should be used if the server cannot process the enitity, e.g. if a image cannot be formatted Or mandatory fields is missing in the payload.

500–internal Server ERROR–API Developers should avoid this Error. If An error occurs in the global Catch blog, the stracktrace should is logged and not returned as response.

Use error payloads

All exceptions should is mapped in an error payload. Here's an example what a JSON payload should look like.

{"  errors": [   {    "usermessage": "Sorry, the requested resource does not exist",    "Internalmessage": "No Car found in the database ",    " code ": $,    " More info ":" http://dev.mwaysolutions.com/blog/api/v1/errors/12345 "   }  ]}
Allow overriding HTTP method

Some proxies support only POST and GET methods. To support a RESTful API with these limitations, the API needs a-to override the HTTP method.

Use the custom HTTP Header x-http-method-override to overrider the POST Method.

"Referred from http://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/"

Restful API Best Practices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.