REST API with JSON
What is REST API?
REST stands for Representational State Transfer. It relies on a stateless, client-server, cacheable communications. In most cases it is used with the HTTP protocol.
RESTful applications use HTTP requests to POST (create), PUT (create and/or update), GET (e.g., make queries), and DELETE data. REST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.
Protocols
HTTP allows different protocols to be used for the communication between the client and the server. We won’t explain all of them but the four most commonly used: GET, PUT, POST and DELETE.
GET, PUT and DELETE should be implemented as idempotent methods. No matter how many times requests are repeated, the result should be the same. POST, on the other hand, should not be idempotent.
GET
GET performs some kind of a query. It does not request any change to the state of the system in any form or way. This does not mean that the server is not performing some change to its state but that the client did not request it. When performing a GET request, server should respond with the result in the form of JSON.
POST
POST is a request to create a new entity. Content of that entity should be enclosed in the request body.
PUT
PUT is similar to POST with a difference that it should create a new entity if one does not exist or modify the existing one.
DELETE
DELETE is a request to delete a specified entity from the server.
Requests to the server
Avoid using non-nouns like getAllBooks or createNewBook. Type of the action to be performed is specified with the HTTP methods GET, POST, PUT and DELETE. URI should specify entity upon which operations should be performed on. For example, GET /books should retrieve books from the server, DELETE /books should delete the book, PUT /books should modify or create the book and POST /book should request creation of the book in the server.
In case of a GET method, the rest of the URI should provide information regarding type of the query server should use to retrieve requested data. Use query parameters within the URI itself. For example, /books should return all books. /books/id/24 should return the book identified with the ID 24. /books/pageSize/25 should return only 25 books.
The rest of methods (POST, PUT and DELETE) should have all the information enclosed in the message body in the JSON format.
Similarly as with the GET method, DELETE might apply to one specific data, subset of data or all of them (if that’s allowed by the server). If one would want to delete one book DELETE /book request would have JSON {id: 24} in the body. Similarly, if one would want to delete books that match some broader criteria, JSON would be {author: ‘Viktor Farcic’}. Finally, if there is no body, all books would be deleted.
POST and PUT work in a similar fashion like DELETE. Their request body has the information what should be created or modified. One could put a single entity into the body of the request PUT /books. That request would create or modify a single book. An example could be {id: 12345, title: ‘Behavior-Driven Development’, author: ‘Viktor Farcic’}. If bulk insert is allowed, multiple entities can be passed as an array [{title: ‘Behavior-Driven Development’, author: ‘Viktor Farcic’}, {title: ‘Continuous Integration’, author: ‘Viktor Farcic’}].
Keep in mind that the server is responsible to verify whether some request is allowed or not. Operation to delete more than one book could be restricted only to certain users and the DELETE request without the body (delete all) can be denied for all users. The ultimate responsibility to decide whether a request is allowed or not is in the hands of the server.
To summarize, GET does not have the body and uses URI to specify entity (i.e. /books) and, when needed, additional query parameters (i.e. id/24). POST, PUT and DELETE should not specify query parameters through the URI but use the message body to pass the information regarding what should be created, modified or deleted.
Responses from the server
Responses from the server should be always in JSON format and consistent. They should always contain meta information and, optionally, data. Consistency allows consumers of our API to know what to expect. Also, it allows us to write less implementation code since some parsing can be performed in a unified way across all request types.
HTTP response already contains status (more information about the status codes can be found in Status Code Definitions). We can enhance that with meta information could contain additional information. Additional information specific to the implementation in the server could be provided with, for example, error and message. As a general rule, when the client receives a response with HTTP status 2XX, the request was successful. Responses with status 4XX represent errors provoked by the client (i.e. mandatory data is missing) and 5XX are server errors.
Data should be specified even when none is sent from the server.
Few examples would be:
{ meta: { }, data: { id: 24, title: 'Behavior-Driven Development', author: 'Viktor Farcic' } }
{ meta: { error: 789, message: 'Title field is required' }, data: { } }
Versioning
Since API will not be the only entry point for HTTP requests, it is often a good idea to differentiate API URIs from others. I tend to put prefix api to all URIs.
It is important to understand that once an API is published and others start using it, we need to make sure that future changes do not break the usage for those who did not update their clients accordingly. For that reason it is a good practice to prefix all API URIs with version number. First one could be called v1, next one v2 and so on. This way we’ll have freedom to implement changes that might potentially introduce incompatibilities as a separate URI.
With those two things in mind, our previous example with book would look something like following: /api/v1/books
Examples
Finally, let’s go through few examples with books.
Request the list of books
Protocol: GET
URI: /api/v1/books
Request body: EMPTY
Response:
{ meta: { }, data: [{ id: 24, title: 'Behavior-Driven Development', author: 'Viktor Farcic' }, { id: 25, title: 'Continuous Integration', author: 'Viktor Farcic' }] }
Description: Requests all books to be retrieved from the server.
Request a single book
Protocol: GET
URI: /api/v1/books/id/24
Request body: EMPTY
Response:
{ meta: { }, data: { id: 24, title: 'Behavior-Driven Development', author: 'Viktor Farcic' } }
Description: Requests the book with ID 24 to be retrieved from the server.
Request book creation
Protocol: POST
URI: /api/v1/books
Request body:
{ id: 24, title: 'Behavior-Driven Development', author: 'Viktor Farcic' }
Response with status 201:
{ meta: { }, data: { uri: /api/v1/books/id/24 } }
Description: Requests the book to be created. Server response is 201 (created) with URI that can be used by the client to retrieve the requested book.
Request the book to be created or modified
Protocol: PUT
URI: /api/v1/books
Request body:
{ id: 24, author: 'Viktor Farcic' }
Response with status 412:
{ meta: { error: 789, message: 'Title field is required' }, data: { } }
Description: Requests the book to be modified or created. Server response is 412 (precondition failed) with error code and message describing the problem.
Request the book removal
Protocol: DELETE
URI: /api/v1/books
Request body:
{ id: 24 }
Response with status 202:
{ meta: { }, data: { } }
Description: Requests the book to be removed. Server response is 202 (accepted) meaning that the server accepted the request but the processing has not been completed. In other words, server responded immediately and has the removal pending.
Reference: | REST API with JSON from our JCG partner Viktor Farcic at the Technology conversations blog. |