REST is a popular architectural style for designing web APIs. It helps applications exchange information through a consistent interface. Most REST APIs on the web use HTTP and represent data as JSON.
For example, an Employee Management application can expose a REST API to retrieve employees, create new employees, update their details, and delete records. A website or mobile application can use the same API to perform these operations.
In this tutorial, I will explain what REST is and how REST APIs work. You will learn about REST architectural constraints, resources, URIs, HTTP methods, and status codes. I will use simple examples to explain each concept.
At the end, you will find practical Java tutorials for designing REST APIs and building them with Jersey, RESTEasy, and Spring Boot.
Learn all about REST with Java at https://www.javaguides.net/p/restful-tutorial.html
Master REST API Development with Spring Boot
Want to become a skilled Java backend developer? Learn how to design, build, secure, and test real-world REST APIs using Spring Boot, Spring Security, JWT, Spring Data JPA, Hibernate, and MySQL. Strengthen your practical skills through hands-on projects and step-by-step guidance.
1. REST Introduction
What is REST?
REST stands for Representational State Transfer. It is an architectural style introduced by Roy Fielding in his doctoral dissertation.
REST describes how components in a distributed system should interact. In a REST API, a client works with resources through representations. For example, a client can request an employee resource and receive a JSON representation of that employee.
The term state is important here. A resource has state that can be represented in a response. The client also manages its own application state as it follows links and interacts with resources. REST does not simply mean transferring any data over HTTP.
REpresentational State Transfer
REST is not a programming language or a framework. It is a set of architectural constraints. HTTP is commonly used to implement REST APIs because it already provides resource identifiers, request methods, headers, and response codes.
REST APIs are useful when different applications need to work with the same backend. For example, a web application, a mobile app, and an administrative dashboard can all use the Employee Management API.
You can read the original explanation in Roy Fielding's REST dissertation.
2. REST Architecture
The diagram below shows the typical REST architecture:
A typical REST API uses a client-server architecture. The client sends an HTTP request to a server. The server processes the request and returns an HTTP response.
- Client: The application that sends a request. It can be a browser, mobile app, or another backend service.
- Server: The application that provides access to resources and handles requests.
- Request: Contains an HTTP method and a target URI. It may also include headers and a body.
- Response: Contains an HTTP status code and response headers. It may also contain a representation of a resource.
- Representation: The format used to describe resource data. JSON is common in REST APIs. XML and HTML can also be used.
For example, a client sends GET /api/employees/10. The server looks for employee 10. If the employee exists, the server can respond with 200 OK and the employee details in JSON format.
3. REST Architectural Constraints
REST defines six architectural constraints. The first five are required. The sixth constraint is optional.
1. Client-Server
The client handles the user interface. The server manages resources and business logic. They can change independently as long as the interface between them remains compatible.
2. Stateless
Each request must contain the information the server needs to process it. The server should not depend on a stored conversation or session context from an earlier request. This does not mean the server cannot store data in a database.
For example, a protected API request can include an access token. The server checks that token for the current request.
3. Cacheable
Responses should indicate whether they can be cached. Caching can reduce repeated work and improve performance. Not every response should be cached. Sensitive or frequently changing data may require different cache rules.
4. Uniform Interface
REST uses a consistent way to identify and work with resources. A client uses resource identifiers and representations rather than depending on a server's internal classes or database tables.
For example, /api/employees/10 identifies an employee resource. The client can retrieve its representation without knowing how the employee is stored.
The uniform interface also includes self-descriptive messages and links that guide clients through available actions.
5. Layered System
A client does not need to know whether it is communicating directly with the application server or through a gateway, proxy, or load balancer. These layers can provide security, caching, and traffic management.
6. Code on Demand (Optional)
A server may send executable code that extends a client's behavior. JavaScript delivered to a browser is a familiar example. Most JSON-based REST APIs do not use this optional constraint.
Read more about constraints at https://www.javaguides.net/2018/06/rest-architectural-constraints.html
4. REST Key Concepts
Resource
A resource is something your application makes available through its API. It can be an employee, an order, a product, or a collection of records.
In REST API design, it is helpful to identify resources before deciding which URLs and HTTP methods to use.
Example 1: Resources for an Employee Management System:
- Employee
- Department
- Projects
- Task
- Address
Example 2: Resources for a Student Management System:
- Student
- Teacher
- School
- Class
- Subject
URI - Uniform Resource Identifier
A URI (Uniform Resource Identifier) identifies a resource. In web APIs, resource URIs usually look like URLs.
Use clear nouns in resource paths. For example, /api/posts represents a collection of posts and /api/posts/2 identifies one post.
Consider that we are developing a simple blog application. You can define URIs for a blog Post resource as follows:
GET http://localhost:8080/api/posts— Retrieves posts.GET http://localhost:8080/api/posts/2— Retrieves post 2.POST http://localhost:8080/api/posts— Creates a post.PUT http://localhost:8080/api/posts/2— Replaces the state of post 2 with the supplied representation.DELETE http://localhost:8080/api/posts/2— Requests deletion of post 2.
The URI identifies the resource. The HTTP method tells the server which operation the client wants to perform.
Sub-resource
Sub-resource URLs can show a relationship between resources. For example, a blog post may have many comments.
These are common URI patterns:
GET /{resource}/{resource-id}/{sub-resource}
GET /{resource}/{resource-id}/{sub-resource}/{sub-resource-id}
POST /{resource}/{resource-id}/{sub-resource}
Example:
GET /posts/{post-id}/comments
GET /posts/{post-id}/comments/{comment-id}
POST /posts/{post-id}/comments
Nested URLs are useful when the parent provides important context. They are not limited to objects that cannot exist independently. Keep the paths reasonably short and avoid deeply nested URLs.
HTTP Methods
HTTP methods describe the action a client wants to perform on a resource.
- GET: Retrieves a resource or a collection. A GET request should not change the resource's state.
- POST: Submits data for processing. It is commonly used to create resources.
- PUT: Creates or replaces the state of a resource at a known URI, depending on the API.
- PATCH: Applies a partial change to a resource. For example, it can update only an employee's phone number.
- DELETE: Requests that a resource be removed.
GET is a safe method. PUT and DELETE are idempotent methods. This means repeating the same intended operation should have the same effect on the target resource as performing it once. POST is not generally idempotent.
Read more about HTTP methods at REST API - HTTP Methods
HTTP Status Codes
Some of the frequently used HTTP status codes are as follows:
- 200 OK: The request is successful, and the response content is returned to the client as appropriate.
- 201 Created: The request is successful, and a new resource is created.
- 400 Bad Request: The server failed to process the request because of malformed syntax in the request. The client can try again after correcting the request.
- 401 Unauthorized: Authentication is required for the resource. The client can try again with appropriate authentication.
- 403 Forbidden: The server understands the request but refuses to perform it. For example, a regular user may not have permission to delete another user's account.
- 404 Not Found: The requested resource is not found at the location specified in the request.
- 500 Internal Server Error: A generic error message telling that an unexpected error occurred on the server and the request cannot be fulfilled.
Other useful status codes include 202 Accepted for work that has started but is not complete, 204 No Content for a successful operation without a response body, 409 Conflict for a conflicting change, and 429 Too Many Requests when a client exceeds a rate limit.
5. REST API Example: Employee Management
Let's put these concepts together using an Employee Management application.
GET /api/employees— Get all employees. Return200 OKwith the list.GET /api/employees/10— Get employee 10. Return200 OKif found or404 Not Foundif missing.POST /api/employees— Create an employee. Return201 Createdwhen the employee is created.PUT /api/employees/10— Replace employee 10. Return200 OKwith the updated resource or204 No Contentwithout a body.PATCH /api/employees/10— Update selected employee fields. Return200 OKor204 No Contentafter a successful update.DELETE /api/employees/10— Delete employee 10. Return204 No Contentwhen the operation succeeds without a response body.
Example JSON Response
For GET /api/employees/10, the server might return the following JSON:
{
"id": 10,
"firstName": "Alex",
"lastName": "Johnson",
"email": "alex@example.com"
}
The response uses Content-Type: application/json and 200 OK. If the employee does not exist, the API should return an appropriate error response instead.
6. REST API Design Best Practices
These guidelines will help you build APIs that are easier to understand and maintain.
- Use nouns in URLs. Prefer
/api/employeesover/api/getEmployees. - Use HTTP methods correctly. Use GET for reading and POST for creation. Use PUT or PATCH for updates based on the intended operation.
- Return appropriate status codes. Do not return
200 OKfor every result. - Validate incoming data. Reject invalid requests and provide clear error details.
- Support pagination. For large collections, allow clients to request smaller sets of records.
- Protect sensitive endpoints. Use authentication and authorization. Serve production APIs over HTTPS.
- Document the API. Describe endpoints, parameters, request bodies, responses, and errors. OpenAPI is commonly used for this.
7. Build REST APIs with Java: Step-by-Step Guides
Now that you understand the fundamentals, you can start building REST APIs with Java.
If you are new to REST, begin with the REST Basics and API Design sections. Then follow the Spring Boot examples to build CRUD APIs and practice validation, security, documentation, and testing.
7.1 REST Basics
- Overview of REST
- What is Payload in REST API?
- REST API - HTTP Methods
- REST API - HTTP Status Codes
- Advantages of REST
- REST API - REST Architectural Constraints
- REST API - REST Architectural Properties
- REST API - REST Architectural Elements
- Difference Between SOAP vs REST Web Services
7.2 Design REST API Guide
- How to Identify REST Resources
- How to Design URL to REST Resource
- How to Assign HTTP methods to REST Resources
- How to Model JSON Representation Format
- What HTTP Status Code to Return
7.3 REST API Design Best Practices
7.4 Build REST API with Jersey
- Jersey Rest Hello World Example
- Jersey JAX-RS Restful CRUD Web Services Example
- Jersey Rest Developer Guide
7.5 Build REST API with RESTEasy (JAX-RS)
- RESTEasy Hello World Example Tutorial
- RESTEasy JAX-RS Get, POST, PUT and DELETE Tutorial
- RESTEasy Client for GET, POST, PUT, and DELETE RESTFul APIs
7.6 Build REST API with Spring Boot
- Spring Boot CRUD REST API Project using IntelliJ IDEA | Postman | MySQL
- Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial
- Spring Boot, H2, JPA, Hibernate Restful CRUD API Tutorial
- Spring Boot File Upload / Download Rest API Example
- Search REST API using Spring Boot, Spring Data JPA, and MySQL Database
- Spring Boot Login REST API using Spring Security and MySQL
- Login and Registration REST API using Spring Boot, Spring Security, Hibernate, and MySQL Database
- Spring Boot REST API Documentation with Swagger
- Spring Boot Unit Testing CRUD REST API with JUnit and Mockito
- Spring Boot Integration Testing MySQL CRUD REST API Tutorial
Conclusion
REST provides a consistent way to design APIs around resources. The main ideas are simple: identify resources with URIs, use HTTP methods correctly, and return meaningful responses.
Start with a small API such as Employee Management. Practice GET, POST, PUT, PATCH, and DELETE operations. Once you are comfortable with the basics, follow the Spring Boot tutorials above to build a complete REST API with persistence, security, documentation, and tests.
Comments
Post a Comment
Leave Comment