5 Basic REST API Design Guidelines
These guidelines from Guy Levin are intended to help you in creating clean, easy to use, and easily understandable APIs.
Join the DZone community and get the full member experience.
Join For Freeas soon as we start working on an api, design issues arise. a robust and strong design is a key factor for api success. a poorly designed api will indeed lead to misuse or–even worse–no use at all by its intended clients (application developers).
creating and providing a state of the art api requires taking into account:
- restful api principles as described in the literature ( roy fielding , martin fowler , http specification, etc.).
- the api practices of the web giants like google, microsoft, facebook, paypal and other big companies.
designing a rest api raises questions and issues for which there is no universal answer. rest best practices are still being debated and consolidated, which is what makes this job fascinating.
here are the 5 basic design guidelines that make a restful api :
- resources (uris)
- http methods
- http headers
- query parameters
- status codes
let's go over each one and explain a bit.
1. resources (uris)
names and verbs
to describe your resources, use concrete names and not action verbs.
for decades, computer scientists used action verbs in order to expose services in an rpc way, for instance:
getuser(1234)createuser(user)deleteaddress(1234)
by contrast, the restful approach is to use:
get /users/1234post /users (with json describing a user in the body)delete /addresses/1234
uri case
when it comes to naming resources in a program, there are 3 main types of case conventions: camelcase, snake_case, and spinal-case. they are just a way of naming the resources to resemble natural language while avoiding spaces, apostrophes, and other exotic characters. this habit is universal in programming languages where only a finite set of characters is authorized for names.
camelcase
camelcase has been popularized by the java language. it intends to emphasize the beginning of each word by making the first letter uppercase. e.g. camelcase, currentuser, etc. aside from debates about its readability, its main drawback is to be ineffective in contexts which are not case sensitive.
snake_case
snakecase has been widely used for years by c programmers, and more recently in ruby. words are separated by underscores “”, thus letting a compiler or an interpreter understand it as a single symbol, but also allowing readers to separate words fluently. however, its popularity has decreased due to a lot of abuses in c programs with over-extended or too short names. unlike camel case, there are very few contexts where snake case is not usable. examples: snakecase, currentuser, etc.
spinal-case
spinal-case is a variant of snake case which uses hyphens “-” to separate words. the pros and cons are quite similar to those of snake case, with the exception that some languages do not allow hyphens in symbol names (for variable, class, or function naming). you may find it referred to as lisp-case because it is the usual way to name variables and functions in lisp dialects. it is also the traditional way of naming folders and files in unix and linux systems. examples: spinal-case, current-user, etc.
according to rfc3986, urls are “case sensitive” (except for the scheme and the host).
in practice, though, a sensitive case may create dysfunctions with apis hosted on a windows system.
it is recommended to use spinal-case (which is highlighted by rfc3986), this case is used by google, paypal and other big companies.
2. http methods
as stated earlier, one of the key objectives of the rest approach is using http as an application protocol in order to avoid shaping a homemade api. hence, we should systematically use http verbs to describe what actions are performed on the resources and facilitate the developer’s work handling recurrent crud operations.
the following methods are usually observed:
get
the get method is used to retrieve information from the given server using a given uri. requests using get should only retrieve data and should have no other effect on the data.
head
same as get but transfers the status line and header section only.
post
a post request is used to send data to the server, for example, customer information, file upload, etc. using html forms.
put
replaces all current representations of the target resource with the uploaded content.
delete
removes all current representations of the target resource given by a uri.
options
describes the communication options for the target resource.
3. http headers
http header fields provide required information about the request or response, or about the object sent in the message body.
there are 4 types of http message headers:
-
general header : these header fields have general applicability for both request and response messages.
-
client request header : these header fields have applicability only for request messages.
-
server response header : these header fields have applicability only for response messages.
-
entity header : these header fields define meta information about the entity-body or, if no body is present, about the resource identified by the request.
4. query parameters
paging
it is necessary to anticipate the paging of your resources in the early design phase of your api. it is indeed difficult to foresee precisely the progression of the amount of data that will be returned. therefore, we recommend paginating your resources with default values when they are not provided by the calling client, for example with a range of values [0-25].
filtering
filtering consists in restricting the number of queried resources by specifying some attributes and their expected values. it is possible to filter a collection on several attributes at the same time and to allow several values for one filtered attribute.
sorting
sorting the result of a query on a collection of resources. a sort parameter should contain the names of the attributes on which the sorting is performed, separated by a comma.
searching
a search is a sub-resource of a collection. as such, its results will have a different format than the resources and the collection itself. this allows us to add suggestions, corrections, and information related to the search. parameters are provided the same way as for a filter, through the query-string, but they are not necessarily exact values, and their syntax permits approximate matching.
5. status codes
it is very important that as a restful api, you make use of the proper http status codes, especially when mocking restful api .
the mostly used status codes:
200 – ok : everything is working.
201 – created : new resource has been created.
204 – no content : the resource was successfully deleted (no response body).
304 – not modified : the date returned is cached data (data has not changed).
400 – bad request : the request was invalid or cannot be served. the exact error should be explained in the error payload, i.e., „the json is not valid“.
401 – unauthorized : the request requires 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.
500 – internal server error : api developers should avoid this error. if an error occurs in the global catch blog, the stack trace should be logged and not returned as response.
summary
rest is not something new. rest is a return to the web the way it was before the age of the big application server, through its emphasis on the early internet standards, uri, and http.
resource modeling requires a careful consideration based on the business needs, technical considerations (clean design, maintainability, etc.) and cost-benefit analysis of various approaches discussed earlier so that the api design brings out the best api consumer interaction experience.
we went over the basics of designing and developing restful api . these guidelines hopefully will help in creating clean, easy to use, and understandable apis.
Published at DZone with permission of Guy Levin, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments