REST Overview - REST API, HTTP Methods and HTTP Status Codes

In this article, we will take a look into what is REST, REST API, HTTP methods, and HTTP status codes.

1. What is REST?

The REST stands for REpresentational State Transfer. 

-State means data

-REpresentational means formats (such as XML, JSON, YAML, HTML, etc)

-Transfer means carry data between consumer and provider using HTTP protocol

REST is not an architecture; rather, it is a set of constraints that creates a software architectural style, which can be used for building distributed applications.

The REST (REpresentational State Transfer) is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

Like any other architectural style, REST also does have it's own six guiding constraints which must be satisfied if an interface needs to be referred to as RESTful. 

Let's briefly look into six REST architectural constraints:

If you follow all constraints designed by the REST architectural style your system is considered RESTful.

1. Client-Server

This constraint keeps the client and server loosely coupled. In this case, the client does not need to know the implementation details in the server, and the server is not worried about how the data is used by the client. However, a common interface is maintained between the client and server to ease communication.

2. Stateless

The notion of statelessness is defined from the perspective of the server. The constraint says that the server should not remember the state of the application. As a consequence, the client should send all information necessary for execution along with each request, because the server cannot reuse information from previous requests as it didn’t memorize them. All info needed is in the message.

3. Cacheable

This constraint has to support a caching system. The network infrastructure should support a cache at different levels. Caching can avoid repeated round trips between the client and the server for retrieving the same resource.

4. Uniform Interface

The uniform interface constraint at a high level means the interface for a component needs to be as generic as possible. It simplifies and decouples the architecture, which enables each part of the architecture to evolve independently. 

5. Layered System

The server can have multiple layers for implementation. This layered architecture helps to improve scalability by enabling load balancing. It also improves the performance by providing shared caches at different levels. Being the door to the system, the top layer can enforce security policies as well.

6. Code on Demand

The code on demand is an optional constraint. It allows a client to download and execute code from a server. 

Read more about these six REST architectural constraints at https://www.javaguides.net/2018/06/rest-architectural-constraints.html

2. What is a RESTful API?  

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format. 

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

Let's understand some terms which will help you to design and develop REST APIs.

Resources

A RESTful resource is anything that is addressable over the web. By addressable, we mean resources that can be accessed and transferred between clients and servers.

Here are some examples of REST resources:
  • An employee, department, projects in IT company
  • A student in a classroom in a school
  • A search result for a particular item in a web index, such as Google
  • Users of the system.
  • Courses in which a student is enrolled.
  • A user's timeline of posts.
  • The users that follow another user.
  • An article about programming.
REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ global IDs. REST uses various representations to represent a resource were Text, JSON, XML. The most popular representations of resources are XML and JSON.

URI

A URI (Uniform resource identifier) is a string of characters used to identify a resource over the web. In simple words, the URI in a RESTful web service is a hyperlink to a resource, and it is the only means for clients and servers to exchange representations.

The client uses a URI to locate the resources over the web, sends a request to the server, and reads the response. 

For example:

MethodUrlDescription
GET/api/todosGet all todos which belongs to logged in user
GET/api/todos/{id}Get todo by id (If todo belongs to logged in user)
POST/api/todosCreate new todo (By logged in user)
PUT/api/todos/{id}Update todo (If todo belongs to logged in user)
DELETE/api/todos/{id}Delete todo (If todo belongs to logged in user)
The above shows the URI's for Todo resource on the web.

The representation of resources

The representation of resources is what is sent back and forth between clients and servers in a RESTful system. A representation is a temporal state of the actual data located in a storage device at the time of request. 

Different clients can consume different representations of the same resource. Therefore, a representation can take various forms, such as an image, a text file, an XML, or a JSON format. 

For example: Below is the resource JSON representation:
Sign Up -> /api/auth/signup
{
	"firstName": "ramesh",
	"lastName": "fadatare",
	"username": "ramesh",
	"password": "password",
	"email": "javaguides@gmail.com"
}
Log In -> /api/auth/signin
{
	"usernameOrEmail": "ramesh",
	"password": "password"
}

3. HTTP Methods

RESTful web service makes heavy uses of HTTP verbs to determine the operation to be carried out on the specified resource(s). REST APIs enable you to develop any kind of web application having all possible CRUD (create, retrieve, update, delete) operations.

Let's learn about HTTP methods and their role in client-server communication over HTTP.

HTTP GET Method

Use GET requests to retrieve resource representation/information only – and not to modify it in any way. As GET requests do not change the state of the resource, these are said to be safe methods. Additionally, GET APIs should be idempotent, which means that making multiple identical requests must produce the same result every time until another API (POST or PUT) has changed the state of the resource on the server.

If the address is successfully received (error-free), GET returns a JSON or XML representation in combination with the HTTP status code 200 (OK). In case of an error, the code 404 (NOT FOUND) or 400 (BAD REQUEST) is usually returned.

Examples for GET request URI's:

HTTP GET - http://www.usermanagement/api/users/me - Get logged in user profile

HTTP GET - http://www.usermanagement/api/users/{username}/profile - Get user profile by username

HTTP GET - http://www.usermanagement/api/users/{username}/posts - Get posts created by user

HTTP GET - http://www.usermanagement/api/users/{username}/albums - Get albums created by user

http://www.usermanagement/api/users/checkUsernameAvailability - Check if username is available to register

http://www.usermanagement/api/users/checkEmailAvailability - Check if email is available to register

HTTP POST Method

The HTTP POST request is most commonly used to create new resources. When talking strictly in terms of REST, POST methods are used to create a new resource into the collection of resources.

Upon successful creation, an HTTP code 201 is returned, and the address of the created resource is also transmitted in the ‘Location’ header. 

Here are some examples for HTTP POST requests:

HTTP POST - http://www.domain/api/users - Create User

HTTP POST - http://www.domain/api/posts - Create Post

HTTP POST - http://www.domain/api/posts/{postId}/comments - Create new comment for post with id = postId

HTTP PUT Method

Use PUT APIs primarily to update existing resource (if the resource does not exist, then API may decide to create a new resource or not). If a new resource has been created by the PUT API, the origin server MUST inform the user agent via the HTTP response code 201 (Created) response and if an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

Here are some examples for HTTP Put requests:

HTTP PUT - http://www.domain/api/users/{username} - Update user

HTTP PUT - http://www.domain/api/posts/{id} - Update post by id

HTTP PUT - http://www.domain/api/posts/{postId}/comments/{id} - Update comment by id if it belongs to post with id = postId

HTTP DELETE Method

Use DELETE APIs to delete resources (identified by the Request-URI).

A successful response of DELETE requests SHOULD be HTTP response code 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has been queued, or 204 (No Content) if the action has been performed but the response does not include an entity.

Here are some examples for HTTP Delete requests:

DELETE http://www.domain/api/users/{username} - Delete user

DELETE http://www.domain/api/posts/{id} - Delete post 

DELETE http://www.domain/api/posts/{postId}/comments/{id} - Delete comment by id if it belongs to post with id = postId

4. HTTP Status Codes

For every HTTP request, the server returns a status code indicating the processing status of the request. Let's see the frequently used HTTP status codes:

1xx: Information 

Communicates transfer protocol-level information

  • 100: Continue

2xx: Success

This indicates that the client’s request was accepted successfully.

  • 200: OK
  • 201: Created
  • 202: Accepted
  • 204: No Content

3xx: Redirect

This indicates that the client must take some additional action in order to complete their request.

  • 301: Moved Permanently
  • 307: Temporary Redirect

4xx: Client Error

This category of error status codes points the finger at clients.

  • 400: Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not found

5xx Server Error

The server takes responsibility for these error status codes.

  • 500: Internal Server Error
  • 501: Not Implemented
  • 502: Bad Gateway
  • 503: Service Unavailable
  • 504: Gateway Timeout

Conclusion

In this article, we have discussed and understood what is REST, REST API, HTTP methods, and HTTP status codes.

Learn how to develop REST API's using Jersey framework at https://www.javaguides.net/p/restful-tutorial.html

Learn how to develop REST API's using JAX RS with RESTEasy framework at https://www.javaguides.net/2020/01/resteasy-crud-example-tutorial.html

Comments