10 Best Practices for Better RESTful API

20140602_restful_api_checklist_img

Web APIs has become an very important topic in the last year. We at M-Way Solutions are 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 API structure into logical resources. There are used the HTTP methods GET, DELETE, POST and PUT to operate with the resources.

These are 10 best practices to design a clean RESTful API:

1. Use nouns but no verbs

For an easy understanding use 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 not use GET for state changes:

GET /users/711?activate or
GET /users/711/activate

 

3. Use plural nouns

Do not 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 711
GET /cars/711/drivers/4 Returns driver #4 for car 711

 

5. Use HTTP headers for serialization formats

Both, client and server, need to know which format is used for the communication. The format has to be 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 be used to create a better navigation through the API.

{
  "id": 711,
  "manufacturer": "bmw",
  "model": "X5",
  "seats": 5,
  "drivers": [
   {
    "id": "23",
    "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 cars
GET /cars?seats<=2 Returns a list of cars with a maximum of 2 seats

Sorting:

Allow ascending and descending sorting over 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 will 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 use the custom HTTP header: X-Total-Count.

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

Link: <https://blog.mwaysolutions.com/sample/api/v1/cars?offset=15&limit=5>; rel="next",
<https://blog.mwaysolutions.com/sample/api/v1/cars?offset=50&limit=3>; rel="last",
<https://blog.mwaysolutions.com/sample/api/v1/cars?offset=0&limit=5>; rel="first",
<https://blog.mwaysolutions.com/sample/api/v1/cars?offset=5&limit=5>; rel="prev",

 

8. Version your API

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

We are using the url for the API versioning starting with the letter „v“

/blog/api/v1

 

9. Handle Errors with HTTP status codes

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

 

Use HTTP status codes

The HTTP standard provides over 70 status codes to describe the return values. We don’t need them all, but  there should be 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 was invalid or cannot be served. The exact error should be 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 is 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 an image cannot be formatted or mandatory fields are 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 be logged and not returned as response.

Use error payloads

All exceptions should be mapped in an error payload. Here is an example how a JSON payload should look like.

{
  "errors": [
   {
    "userMessage": "Sorry, the requested resource does not exist",
    "internalMessage": "No car found in the database",
    "code": 34,
    "more info": "http://dev.mwaysolutions.com/blog/api/v1/errors/12345"
   }
  ]
} 

10. Allow overriding HTTP method

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

Use the custom HTTP Header X-HTTP-Method-Override to overrider the POST Method.

61 thoughts on “10 Best Practices for Better RESTful API

  1. Eduardo WB

    Thank you for the best practices! I always look forward to do things in the right way, and that list helped me in that goal.

    Reply
  2. Pingback: 10 Best Practices for Better RESTful API - Rakki Studio

  3. Simon Wood

    You might want to change section 8. Versioning should ideally be in the header not in the path. If you can get it into the header then the URI for a resource does not change between versions which is what you would want.

    Reply
    1. Gauthier Delacroix

      That’s not that simple…in a RESTful API, one URL == one resource. Different API versions implies different resource representations, that can be considered as different resources…
      I’m actually not a big fan of header controlled APIs because you have to know, for each option, whether it’s controlled by a header or the URL or POST data. That means that you have to spend more time reading the doc (HATEOAS APIs aim at being usable without reading any doc).

      Header controlled APIs are harder to use. If you want your API to be popular, the best is to keep it as simple as possible…

      Reply
      1. Simon Wood

        The main reason I don’t like like the version in the URI is because each URI == One resource.

        If I have an API that returns pens http://domain.com/pens/ and I can get pen 10 http://domain.com/pens/10/ I now change the interface of my API, I change the a key in the JSON reply. This is a breaking change so I now need to update the version, but pen 10 is still pen 10. There is only one pen 10 and its URI is http://domain.com/pens/10/. If version was in the URI I would have two pen 10’s but in the real/physical world there is only one pen 10. It is the interface to this pen that has changed so using the header makes sense.

        If I talk you in english, it is you. If I then change interface and talk to you in spanish, it is still you. You have not change just the interface I am using to communicate with you. You would need a single never changing URI.

        I agree with you for beginners version in the URI is easier to consume.

        Reply
        1. Karl Rainhold

          I would concur that a consistent path prevents consumers from having to update their applications when the version change might be minor, while it does make sharing the responses and clearly knowing from logs which version was requested more problematic.

          So what happens when you provide more than one format, like XML or JSON, on the same service? That’s fine if you are not caching the responses. If the service responses are cacheable, then your cache-key needs to be able to distinguish the responses that are populating the cache. If those responses are dependent on the request header, you have just made your CDN configuration much more complex, and you may have reduced or eliminated the cacheability.

          This begs a different question on versioning, one of parallel versus serial. If you want to provide a flexible service, consumed in more than one way, then you either effectively have multiple service paths for the same service but different output formats, or you have the same path with the headers (request and response) distinguishing what the payload looks like. Protecting your origin and scaling your offering becomes more of challenge going the header route.

          Reply
          1. Robert

            I’m in support of having major versions as part of the path. It’s the best way to continue support for legacy software without restricting future releases of your API.

            For example, say your API has an endpoint for cars, /api/cars. Then, one day you realize that “automobiles” is a more accurate description, so you change the endpoint to /api/automobiles. Naturally, this means updating any references returned in other requests, so any arrays for "cars" would change to "automobiles" throughout the rest of the API.

            So what happens to all of the software developed using the original API? Either you support both calls and return redundant data, bloating the response, or you’re forced to update the software, which isn’t always a quick thing depending on the outlet (iOS?)

            If you include the version in the path, then the original endpoint /api/v1/cars can continue to live on, while fundamental changes move to a new path /api/v2/automobiles.

            Sorry for resurrecting this, just thought it was worth mentioning for future readers.

        2. Nick

          “If version was in the URI I would have two pen 10’s but in the real/physical world there is only one pen 10”

          Not quite; there is still only one pen 10, but you would have two ways to reach that pen, and it’s explicit for someone new to the code which API version is being used. Without an explicit version, at best a developer will have to go digging to find out which API version is used, and at worst, they won’t do that and they’ll reference the wrong documentation and introduce bugs.

          Reply
    2. Shyju

      Service versioning is an important concept in middleware/integration technology and version should be in the path for maintaining multiple versions at a time.
      For example,
      Suppose a service is consumed by multiple end applications and the service provider what to change the service output format or add some more data in it. In this case, it is import to maintain the previous version of the service to ensure that the change of the service will not effect to the business. The consuming application will not be in a position to make the necessary changes inline with service provider because of various reasons like budget constraint, release schedule etc. So in this case who ever wants, they can continue with existing version until a period of time. For new application or some of the application can migrate to new version based on the convenience.

      Reply
  4. Pingback: Ashlabs | Pearltrees

  5. Pingback: 【コンピューター】 ある中級プログラマの告白 | POSTD 2014年06月24日 深夜便 | aquadrops * news

  6. abatishchev

    Plural vs singular is very controversial and you can’t just say do this way or that way. Here it’s just a matter of taste. Like SQL tables. I name them in plural but web api controllers in singular.

    Reply
    1. jack

      I think the point was more to use only plural or singular.

      Instead of having /cars return a list of all cars and /car/ID return a specific car.

      After all, consistency *IS* key.

      Reply
      1. Kepro

        for my is better api cars is list of cars and i want car from list with id 711 then i call cars/711 like cars get by id 711 🙂

        Reply
    2. FIRAT KÜÇÜK

      IMHO singular is better. Because we define an entity. I use singular names both in DB tables and REST URLs. And automatic tools that generate REST URLs or tables cannot find the plural form of the entities.

      Reply
  7. alan bauman

    Just wanted to let you know I’ve adapted your post to our Corporate API guidelines. Thanks for the giant step forward!

    Reply
  8. Pingback: jesse

  9. Pingback: 10 Best Practices for Better RESTful API | Thin...

  10. Vincent

    I haven’t really tried this, but I was wondering – does HTML/HTTP/REST implemented with various serverside languages have a provision for inequality operators in the querystring?

    i.e. GET /cars?seats<=2 Returns a list of cars with a maximum of 2 seats

    How does one parse this URL path? I was unaware that standard querystring manipulators would recognize this in any meaningful way. If it weren't for an odd-looking variable name, I'd think you'd get something like Request.QueryString("seats<") evals to "2" ?

    Reply
    1. Jerode

      I have been using the recommendation for filtering for your scenario:
      gt – Greater than
      lt – Less than
      eq – Equal to
      ge – Greater than or equal to
      le – Less than or equal to

      Example GET /cars?seats le 2

      Reply
    1. Fritz Lekschas

      I absolutely agree and would definitely use dot notation and also follow semantic versioning. I don’t see a point in over simplifying things here. While I’d agree that the resource itself may not change, the interface changes.

      Reply
    2. Frank

      Usually dot notation is meant to distinguish between minor and major releases.

      This way when you do a bug fix and update from v1.01 to v1.02, people do not need to update their URL.

      Having the major version in the URL can help if you decide to keep a legacy API for old customers, or have LTS versions. For example, if you make a major change that is not backward compatible, you can change to v2.0 and the only two URLs would be /v1 and /v2.

      This way if you make a change to the resource structure (maybe the new version changes how an object or data is structured to be more organized or intuitive) new consumers can use the new version, while old ones do not need to update their code.

      Reply
    3. Markus Pfeiffer

      I agree with Frank’s points. Public APIs should be relatively stable for (backwards) compatibility’s sake. Breaking your API with every minor release is a bad idea. I would only add a /v2 if it’s fundamentally different and you need to keep both sets of APIs available at the same time. I would also suggest to make the API version independent from the software version. I.e. just because your software is now at v2.0 doesn’t mean you API has to change/break.

      If you add a new endpoint with a new software release (which doesn’t break the API) then only your updated clients will know about it, so I don’t see any advantage to adding the new endpoint below /v1.1.

      If your new client needs to talk to servers which don’t provide this new endpoint yet, you’ll need some way to query the exact server version anyway. Unless you want to guess the version by 404ing on certain endpoints.

      Reply
  11. johnvuong

    Is there any good idea to support many to many relation?the Many-to-Many relationship appears between Book and Author. One book may have no or many authors books, one author may authored no or many books.

    Reply
  12. Martin

    I would be careful with returning 204 for deleted because it implies empty response:
    “The 204 response MUST NOT include a message-body”

    But there might be some business logic which requires returning something after deletion.

    Reply
  13. Pingback: RESTful API URI 设计: 查询(Query)和标识(Identify) – 田园里的蟋蟀 | 查问题

  14. Pingback: Build a Better API - Mahmoud Zalt (BLOG)

  15. mcvole

    Nice article thanks.

    If drivers can exist without a car, would you offer both URIs:

    /cars/711/drivers/4
    /drivers/4

    And if so would the driver ids be the same e.g. 4?

    Reply
    1. Markus Pfeiffer

      Here’s my 2 cents: Since cars and drivers can be independent, I don’t think you want cars and drivers. What you want are cars, persons and car-person-relations (which you could call drivers). This may seem like nitpicking, but I’m a firm believer that good naming is an important aspect of creating a good API. So your endpoints would be:

      ../persons/{id}
      ../cars/{id}
      ../cars/{id}/drivers/{id}

      Back to your original question:
      Should ../cars/{id}/drivers/{id} return the same entity as ../persons/{id}.

      Think about the intended purpose of the drivers endpoint. Will it return the current driver(s) of a car, or should it provide additional information? To me cars/{id}/drivers suggests that it simply returns current driver(s) of a car, which is a person.

      For flexibility’s sake I would actually lean towards returning a different entity. Meaning drivers should return the relation between this car and the persons that are/used to be drivers. This entity could then contain additional information (e.g. current-driver, drive-count, distance-traveled etc.).

      If you always need full information about the person when querying drivers, you could return the person as a nested object of the relation. Otherwise the relation could simply contain the id and you could do another lookup when required.

      Reply
      1. Yves

        I like your suggestion, and I have exactly the same structure as the one you suggest.
        But I am facing a problem : I would like to do statistics on the drivers, cars, etc. eg.

        1. I’d like to be able to get how often the cars have been used by drivers male of more than 25 years.
        I do multiple GET queries on /cars/drivers with query parameters that allow me to filter with my driver profile. or I use the HEADER with x-total-count. OK

        2. If I want to know what cars prefer the male drivers of more than 25 years. I am obliged through all my cars, get their drivers, and see their gender and age. Or I should create :
        persons/{i}/cars

        3. and finally, if I want to know how many blue cars were used by more than 25-year drivers, I woud probably need to invent a new resource /drivesession with mixed attributes of cars and persons

        Or should I create a specific ressource /statistics which gives me tables of stats already preprocessed?

        What is your recommandation?

        Reply
      2. novody

        An example realation between entities.

        ../cars/{id}/drivers/{id}
        [{
        "reference": "../persons/1"
        }, {
        "reference": "../persons/2"
        }, {
        "reference": "../persons/3"
        }, {
        "reference": "../persons/4"
        }, {
        "reference": "../persons/5"
        }]

        Reply
  16. Mark

    Am trying to stick to a Restful design pattern for both JSON and HTML. My issue is the design for creating a new resource (amongst others, but this is the gist of the issue). IE:
    JSON – POST to /resource creates a new resource.
    JSON – GET to /resource shows a resource.
    HTML – POST to /resource creates a new resource.
    HTML – GET to /resource shows a resource.
    All good so far – but I need a HTML form actually create the data to send to the HTML POST. Obviously POST and GET already do things. I could use:
    HTML – GET to /resource?create (or) GET to /resource?action=create
    But that seem’s like a kludge and not intuitive.
    Any thoughts or ideas?

    Reply
    1. Mark

      Replying to myself (bad form, I know).
      The URLs above should have been.

      JSON – POST to /resources creates a new resource.
      JSON – GET to /resources/id shows a resource.
      HTML – POST to /resources creates a new resource.
      HTML – GET to /resources/id shows a resource.
      HTML – GET to /resources shows a list of resources.

      Maybe I make the URL
      HTML – GET to /resources/NEW
      Which would show the HTML form to create a new resource which sends the POST, and keep a few keywords reserved. But really this is just a variation of the original post.

      Reply
  17. Meyyappan Muthuraman

    This is the best REST resource I have read so far. Thanks a lot.
    Very Very Very useful.

    Reply
  18. Gilberto

    Where can i read About best Practices of this Best Practises to get The Values in the Code ?

    Reply
  19. Pingback: 링크 모음 | my tech links

  20. Pingback: Global Pagination in WebAPI using ActionAttributeFilter | VisualBean

  21. Pingback: It’s time to look back over the blog highlights 2015 | Thinking Mobile

  22. Say

    I like this article very much! I’ve gotten a hold of node and express so am looking for this type of article. Im glad you’ve written and shared this article. Less of a headless programmer now.

    Reply
  23. Mike

    Hi Stefan – this is an outstanding post. Thank you. I am curious, does there exist a reference implementation, or perhaps a scaffolding project for NPM (or some other language) in the works to template these guidelines? Would you be interested in collaborating on such a project?

    Reply
  24. Pingback: Automating Network Provisioning with Cisco APIC — Exploring the REST API – Oliver's Blog

  25. zhuguowei

    hi,
    Thanks, What about update some product’s status?
    POST products/1/status
    status : 1

    Reply
  26. Pingback: Best practise to define well formed REST API – Technology serves life

  27. Pingback: Best practise to define well formed REST API – Technology serves life

  28. Pingback: Week 10 – Stage RealDolmen 2016

  29. Pingback: REST API Best practices – Alexandru Bereghici

  30. Rainer

    Hi Stefan,
    I have lots of entities, for which I have to implement REST services supporting filtering und pagination. So I created a class PaginationQueryParams which I use with @BeanParam PaginationQueryParams paginationQueryParams in my REST resource implementation.
    The problem now is, how to annotated the filtering as described in section 7of your article, because I don’t now which fields the filtering is applied!
    Thnx, Rainer

    Reply
  31. Pingback: Rest |

  32. Pingback: Best practices for better REST API – Lessons 4 Dev

  33. Pingback: REST Web Services | techyholmes

Leave a Reply

Your email address will not be published. Required fields are marked *