Name some best practices for better RESTful API design

Technology CommunityCategory: API DesignName some best practices for better RESTful API design
VietMX Staff asked 3 years ago
  • Use nouns and HTTP methods but no verbs
GET /cars
POST /cars
DELETE /cars/:id
instead
GET /getAllCars
POST /createNewCar
GET /deleteAllRedCars
  • GET method and query parameters should not alter the state
  • Use plural nouns
/cars instead of /car
/users instead of /user
/products instead of /product
/settings instead of /setting
  • Use sub-resources for relations
GET /cars/711/drivers/ Returns a list of drivers for car 711
GET /cars/711/drivers/4 Returns driver #4 for car 711
  • Use HTTP headers for serialisation formats
Content-Type defines the request format.
Accept defines a list of acceptable response formats.
  • 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"
		}]
	}]
}
  • Use appropriate HTTP response status codes
  • 2xx (Success category)
  • 3xx (Redirection Category)
  • 4xx (Client Error Category)
  • 5xx (Server Error Category)
  • Provide filtering, sorting, field selection and paging for collections
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
  • Version your API
/blog/api/v1
  • Use error payloads – All exceptions should be mapped in an error payload.
{
	"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"
	}]
}
  • Allow overriding HTTP method

    In certain situations (for example, when the service or its consumers are behind an overzealous corporate firewall, or if the main consumer is a web page), only the GET and POST HTTP methods might be available. In such a case, it is possible to emulate the missing verbs by passing a custom header in the requests. To support a RESTful API with these limitations, the API needs a way to override the HTTP method and use the custom HTTP Header X-HTTP-Method-Override to map the request to an appropriate API method.