Implementing HTTP GET, POST, PUT, PATCH, and DELETE
Course: Advanced Java Training
Topic: Implementing HTTP GET, POST, PUT, PATCH, and DELETE
Course Link: Advanced Java Training – JustAcademy
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to HTTP Methods
HTTP methods define the intended action a client wants to perform on a resource hosted by a server. In RESTful web services, these methods are used to retrieve, create, replace, partially update, and delete resources.
In Java development, Spring Boot provides annotations such as @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping to map HTTP requests to controller methods.
For example, an employee management application may use GET to retrieve employee information, POST to create an employee, PUT to replace employee data, PATCH to update selected fields, and DELETE to remove an employee.
Learning Objectives
- Understand the purpose of HTTP methods in REST APIs.
- Learn the differences between GET, POST, PUT, PATCH, and DELETE.
- Implement CRUD operations using Spring Boot.
- Understand request bodies, path variables, and HTTP status codes.
- Test REST API endpoints using Postman and curl.
- Apply validation, error handling, and API security best practices.
2. Understanding CRUD Operations
CRUD stands for Create, Read, Update, and Delete. These are the four fundamental operations used to manage data in most applications.
| CRUD Operation |
HTTP Method |
Purpose |
Example |
| Create |
POST |
Create a new resource. |
Add a new employee. |
| Read |
GET |
Retrieve existing information. |
View employee details. |
| Update |
PUT or PATCH |
Replace a resource or modify selected fields. |
Update employee information. |
| Delete |
DELETE |
Request removal of a resource. |
Delete an employee record. |
Example REST API Endpoints
GET /api/employees
GET /api/employees/101
POST /api/employees
PUT /api/employees/101
PATCH /api/employees/101
DELETE /api/employees/101
Here, /api/employees represents the employee collection, while /api/employees/101 identifies an individual employee resource.
3. Understanding HTTP GET
The GET method retrieves information from a server. It is commonly used to fetch a collection of resources or a particular resource without requesting a change to the resource's state.
Characteristics of GET
- Used to retrieve information.
- Should not be used to modify server-side resource state.
- Is defined as a safe and idempotent HTTP method.
- Can support caching when the response and request conditions permit it.
- Usually returns a response body containing JSON, XML, or another representation.
Example GET Requests
GET /api/employees
GET /api/employees/101
The first request retrieves the employee collection. The second retrieves the employee identified by ID 101.
Implementing GET in Spring Boot
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@GetMapping
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@GetMapping("/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employeeService.getEmployeeById(id);
}
}
This example assumes that EmployeeService provides the corresponding methods and that missing employee IDs are handled appropriately, for example by throwing an exception mapped to HTTP 404.
Important GET Annotations
@RestController declares a REST controller.
@RequestMapping defines the common endpoint path.
@GetMapping maps HTTP GET requests.
@PathVariable extracts a value from the URL path.
Example GET Response
{
"id": 101,
"name": "Rahul Sharma",
"email": "[email protected]",
"department": "IT"
}
A successful request commonly returns HTTP 200 OK. If the requested employee does not exist, the API should return HTTP 404 Not Found.
4. Understanding HTTP POST
The POST method submits data to a server for processing. In REST APIs, it is commonly used to create a new resource within a collection.
Characteristics of POST
- Commonly creates new resources.
- Usually sends data through the request body.
- May trigger business operations or other processing.
- Is not inherently idempotent.
- Often returns HTTP 201 Created when a resource is successfully created.
Example POST Request
POST /api/employees
Content-Type: application/json
Accept: application/json
{
"name": "Priya Patel",
"email": "[email protected]",
"department": "Human Resources"
}
Implementing POST in Spring Boot
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@PostMapping
public ResponseEntity<Employee> createEmployee(
@RequestBody Employee employee) {
Employee savedEmployee =
employeeService.createEmployee(employee);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(savedEmployee);
}
}
The @RequestBody annotation allows Spring to deserialize the incoming JSON into an Employee object. The service validates and persists the data and returns the saved employee.
Example POST Response
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/employees/102
{
"id": 102,
"name": "Priya Patel",
"email": "[email protected]",
"department": "Human Resources"
}
The ID and response shown are illustrative. A real application should return the identifier assigned by its persistence layer.
Important POST Annotations
@PostMapping maps HTTP POST requests.
@RequestBody reads the request body.
ResponseEntity provides control over the HTTP response.
HttpStatus.CREATED represents status code 201.
5. Understanding HTTP PUT
The PUT method requests that a resource be created or replaced at a known target URI, depending on the API's design and server capabilities. In an update operation, PUT generally replaces the resource's represented state rather than modifying only selected fields.
Characteristics of PUT
- Commonly replaces a resource at a known URI.
- Can support creating a resource at a known URI when the server permits it.
- Is defined as an idempotent HTTP method.
- Usually sends the replacement representation in the request body.
- May return HTTP 200 OK, 204 No Content, or another appropriate status.
Example PUT Request
PUT /api/employees/102
Content-Type: application/json
{
"name": "Priya Patel",
"email": "[email protected]",
"department": "Finance"
}
In a full-replacement design, the request contains the complete set of fields that the API expects to replace. The API must document how omitted fields are handled.
Implementing PUT in Spring Boot
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@PutMapping("/{id}")
public ResponseEntity<Employee> updateEmployee(
@PathVariable Long id,
@RequestBody Employee employee) {
Employee updatedEmployee =
employeeService.updateEmployee(id, employee);
return ResponseEntity.ok(updatedEmployee);
}
}
The service should check whether the employee exists, validate the replacement data, update the record, and handle missing resources consistently.
Example PUT Response
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 102,
"name": "Priya Patel",
"email": "[email protected]",
"department": "Finance"
}
PUT Best Practices
- Define whether PUT performs full replacement or follows a documented resource-specific contract.
- Validate all required fields.
- Do not accidentally reset omitted fields without a clear replacement policy.
- Use the target resource ID from the path to identify the resource.
- Return appropriate responses when the resource is missing or invalid.
6. Understanding HTTP PATCH
The PATCH method applies partial modifications to an existing resource. Unlike a full-replacement PUT request, a PATCH request generally includes only the fields or changes that need to be applied.
Characteristics of PATCH
- Used for partial resource updates.
- Usually includes only the fields being changed.
- Is not inherently idempotent; idempotency depends on the patch operation.
- Can use JSON-based patch formats or a documented application-specific format.
- Should define how missing fields, null values, and invalid changes are handled.
Example PATCH Request
PATCH /api/employees/102
Content-Type: application/merge-patch+json
{
"department": "Marketing"
}
This example uses JSON Merge Patch semantics, in which the supplied department field is changed while other fields are generally preserved. Under JSON Merge Patch, null values have a defined meaning and can be used to remove object members.
Implementing a Simple PATCH Endpoint in Spring Boot
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@PatchMapping("/{id}")
public ResponseEntity<Employee> patchEmployee(
@PathVariable Long id,
@RequestBody Map<String, Object> changes) {
Employee updatedEmployee =
employeeService.patchEmployee(id, changes);
return ResponseEntity.ok(updatedEmployee);
}
}
This controller delegates the partial-update behavior to the service. The service must allowlist supported fields, validate types and values, handle nulls intentionally, and reject unsupported changes. If the API accepts JSON Merge Patch, configure and document that media type and its semantics explicitly.
Example PATCH Response
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 102,
"name": "Priya Patel",
"email": "[email protected]",
"department": "Marketing"
}
PATCH Best Practices
- Update only the fields included in the patch operation.
- Never bind arbitrary client-supplied fields directly to sensitive entities.
- Validate each field and handle missing or null values correctly.
- Document the accepted patch format and content type.
- Consider ETags and conditional requests when concurrent updates are a concern.
7. Understanding HTTP DELETE
The DELETE method requests removal of a resource identified by its URI. The server may remove the resource permanently, mark it as deleted, or apply another documented deletion policy.
Characteristics of DELETE
- Requests the removal of a resource.
- Identifies the target resource through the request URI.
- Is defined as an idempotent HTTP method.
- May return HTTP 204 No Content when deletion succeeds without a response body.
- May return HTTP 200 OK when the server returns a response representation.
Example DELETE Request
DELETE /api/employees/102
Implementing DELETE in Spring Boot
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEmployee(
@PathVariable Long id) {
employeeService.deleteEmployee(id);
return ResponseEntity.noContent().build();
}
}
The service should verify the resource and perform the intended deletion. If the employee does not exist, the application should follow its documented policy, commonly returning HTTP 404 Not Found.
Example DELETE Response
HTTP/1.1 204 No Content
A 204 response has no response body. DELETE is idempotent in its intended effect, even if repeated requests return different status codes.
8. Comparison of GET, POST, PUT, PATCH, and DELETE
| Feature |
GET |
POST |
PUT |
PATCH |
DELETE |
| Primary Purpose |
Retrieve data |
Create or process data |
Create or replace resource state |
Partially modify a resource |
Remove a resource |
| Request Body |
Usually absent |
Commonly present |
Commonly present |
Commonly present |
Optional and uncommon |
| Safe |
Yes |
No |
No |
No |
No |
| Idempotent |
Yes |
Not inherently |
Yes |
Depends on the patch operation |
Yes |
| Typical Success Status |
200 OK |
201 Created |
200 OK or 204 |
200 OK or 204 |
204 No Content |
9. Complete CRUD API Design Example
A well-designed employee API uses a consistent resource path and different HTTP methods for different operations.
| Method |
Endpoint |
Action |
Typical Status |
| GET |
/api/employees |
Retrieve all employees. |
200 OK |
| GET |
/api/employees/101 |
Retrieve one employee. |
200 OK or 404 |
| POST |
/api/employees |
Create an employee. |
201 Created |
| PUT |
/api/employees/101 |
Replace employee data. |
200 OK or 204 |
| PATCH |
/api/employees/101 |
Update selected fields. |
200 OK or 204 |
| DELETE |
/api/employees/101 |
Delete an employee. |
204 No Content |
10. Testing HTTP Methods with Postman
Postman is a tool for sending HTTP requests and examining API responses. It is commonly used during REST API development and debugging.
Testing GET
- Open Postman and create a new HTTP request.
- Select GET as the method.
- Enter
http://localhost:8080/api/employees.
- Click Send.
- Check the response status and JSON body.
Testing POST
- Select POST.
- Enter
http://localhost:8080/api/employees.
- Open Body and select raw JSON.
- Enter a valid employee object.
- Click Send and verify the creation response.
Testing PUT
- Select PUT.
- Enter the employee-specific URL.
- Provide the complete replacement representation expected by the API.
- Send the request and verify the updated resource.
Testing PATCH
- Select PATCH.
- Enter the employee-specific URL.
- Provide only the intended field changes.
- Use the content type required by the API's patch format.
- Verify that unchanged fields remain unchanged.
Testing DELETE
- Select DELETE.
- Enter the employee-specific URL.
- Send the request.
- Verify the success status.
- Send a GET request to check the API's behavior after deletion.
11. Testing HTTP Methods with curl
GET Request
curl -i http://localhost:8080/api/employees/101
POST Request
curl -i -X POST http://localhost:8080/api/employees \
-H "Content-Type: application/json" \
-d '{"name":"Priya Patel","email":"[email protected]","department":"IT"}'
PUT Request
curl -i -X PUT http://localhost:8080/api/employees/101 \
-H "Content-Type: application/json" \
-d '{"name":"Priya Patel","email":"[email protected]","department":"Finance"}'
PATCH Request
curl -i -X PATCH http://localhost:8080/api/employees/101 \
-H "Content-Type: application/merge-patch+json" \
-d '{"department":"Marketing"}'
This PATCH example assumes the API supports JSON Merge Patch. If the endpoint accepts a different patch format, use its documented content type and request structure.
DELETE Request
curl -i -X DELETE http://localhost:8080/api/employees/101
The employee ID and sample values are illustrative. Run these commands against your own application and ensure the test data exists.
12. Input Validation in REST APIs
Input validation ensures that incoming data meets the API's requirements before business logic or database operations are performed. It helps prevent invalid records, unexpected errors, and certain security issues.
Example Employee Model with Validation
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class EmployeeRequest {
@NotBlank(message = "Name is required")
@Size(max = 100, message = "Name must not exceed 100 characters")
private String name;
@NotBlank(message = "Email is required")
@Email(message = "Enter a valid email address")
private String email;
@NotBlank(message = "Department is required")
private String department;
public EmployeeRequest() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
In Spring Boot, include the appropriate validation dependency and use @Valid on the request body parameter to trigger validation.
Example Validated POST Endpoint
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/employees")
public class EmployeeCreateController {
private final EmployeeService employeeService;
public EmployeeCreateController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@PostMapping
public ResponseEntity<Employee> createEmployee(
@Valid @RequestBody EmployeeRequest request) {
Employee employee =
employeeService.createEmployee(request);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(employee);
}
}
The service method shown is illustrative and must be implemented to map the request DTO to the domain or persistence model. Validation failures should be translated into a clear client error response, commonly HTTP 400 Bad Request.
13. Error Handling in REST APIs
Consistent error handling helps API consumers understand what went wrong. Instead of returning unclear messages or internal stack traces, an API should return appropriate HTTP status codes and safe error details.
Common Error Scenarios
| Status |
Scenario |
Recommended Handling |
| 400 Bad Request |
Invalid JSON or validation failure. |
Explain which input fields need correction. |
| 401 Unauthorized |
Missing or invalid authentication. |
Require valid credentials. |
| 403 Forbidden |
Insufficient permissions. |
Deny access to the protected operation. |
| 404 Not Found |
Requested resource does not exist. |
Return a suitable not-found response. |
| 409 Conflict |
Duplicate record or conflicting state. |
Explain the conflict safely. |
| 500 Internal Server Error |
Unexpected server-side failure. |
Log diagnostic details securely and return a generic error. |
Example Exception Handler
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(EmployeeNotFoundException.class)
public ResponseEntity<Map<String, String>> handleNotFound(
EmployeeNotFoundException exception) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(Map.of(
"error", "Employee not found"
));
}
}
The custom EmployeeNotFoundException must be defined by the application. Additional handlers can be added for validation failures and other expected errors. Avoid returning raw exception messages or stack traces to clients.
14. Security Best Practices for HTTP Methods
- Use HTTPS to protect data in transit.
- Authenticate clients where required.
- Check authorization for every protected resource and operation.
- Validate all client-supplied input.
- Prevent mass assignment by exposing dedicated request DTOs.
- Use parameterized database queries or a suitable ORM.
- Apply rate limiting and request-size limits where appropriate.
- Do not treat an unpredictable resource ID as an authorization mechanism.
- Protect destructive operations with proper access controls.
- Keep logs useful without recording passwords, access tokens, or unnecessary personal data.
15. Common Mistakes When Implementing HTTP Methods
| Mistake |
Why It Is a Problem |
Better Practice |
| Using GET to change data |
Violates safe-method expectations and can cause unintended changes. |
Use POST, PUT, PATCH, or DELETE according to the operation. |
| Using POST for every operation |
Makes API behavior less predictable and ignores HTTP semantics. |
Select the appropriate method for each resource operation. |
| Treating PUT as a partial update without documentation |
Clients may misunderstand how omitted fields are handled. |
Document replacement behavior or use PATCH for partial changes. |
| Updating every field in PATCH |
Can overwrite values that the client did not intend to change. |
Apply only explicitly defined patch operations. |
| Returning 200 for every response |
Makes error and operation outcomes less clear. |
Use suitable status codes such as 201, 204, 400, and 404. |
| Skipping validation |
Invalid data can reach business logic or storage. |
Validate request payloads and enforce business rules. |
| Ignoring authorization |
Users may access or modify resources they do not own. |
Apply resource-level authorization checks. |
16. Practical Exercises
- Create a Spring Boot project with a REST controller for employees.
- Implement GET endpoints to retrieve all employees and one employee by ID.
- Implement a POST endpoint to create an employee.
- Implement PUT to replace the editable fields of an existing employee.
- Implement PATCH to update only the department or email field.
- Implement DELETE to remove an employee.
- Return appropriate status codes for successful and unsuccessful operations.
- Add input validation for names, emails, and department values.
- Test all endpoints with Postman or curl.
- Handle missing employee IDs and invalid request bodies.
- Connect the API to a database using Spring Data JPA.
- Protect sensitive endpoints with authentication and authorization.
17. Interview Questions and Answers
Q1. What is the purpose of HTTP GET?
Answer: GET retrieves a representation of a resource without requesting a change to the resource's state. It is safe and idempotent.
Q2. What is the purpose of HTTP POST?
Answer: POST submits data for processing and is commonly used to create resources within a collection.
Q3. What is the difference between PUT and PATCH?
Answer: PUT generally creates or replaces a resource at a known URI, whereas PATCH applies a partial modification using a defined patch format.
Q4. Is DELETE idempotent?
Answer: Yes. Repeating the same DELETE request has the same intended effect on server state, although the response status may differ.
Q5. What is the difference between 200 and 201?
Answer: HTTP 200 indicates success, while HTTP 201 indicates that a resource has been created.
Q6. What is HTTP 204 No Content?
Answer: It indicates that the request succeeded and the response contains no body.
Q7. What does @RequestBody do?
Answer: It binds the HTTP request body to a Java object using a suitable message converter.
Q8. What does @PathVariable do?
Answer: It reads a value from the URL path and assigns it to a controller method parameter.
Q9. Why is @Valid used in a REST controller?
Answer: It triggers validation of a request object when validation constraints and the required validation support are configured.
Q10. Why should GET not be used for deletion?
Answer: GET is defined as a safe method. Using it for deletion can cause unintended changes when browsers, crawlers, or caches access the URL.
Q11. Can POST be idempotent?
Answer: POST is not inherently idempotent, but an API can implement an idempotency mechanism, such as an idempotency key, for suitable operations.
Q12. What is the purpose of ResponseEntity?
Answer: ResponseEntity allows a controller to specify the response body, HTTP status code, and headers.
18. Quick Revision Checklist
- GET retrieves resources.
- POST commonly creates resources or submits processing requests.
- PUT creates or replaces resource state at a known URI.
- PATCH applies partial modifications.
- DELETE requests resource removal.
- GET is safe and idempotent.
- PUT and DELETE are idempotent by HTTP semantics.
- POST is not inherently idempotent.
- PATCH idempotency depends on the patch operation.
- Use appropriate status codes and validate request bodies.
- Test APIs with Postman, curl, and automated tests.
- Apply authentication, authorization, and secure error handling.
19. Conclusion
HTTP methods are fundamental to building well-structured REST APIs. GET retrieves information, POST submits data and commonly creates resources, PUT replaces resource state, PATCH applies partial updates, and DELETE requests resource removal.
Spring Boot simplifies the implementation of these operations through request-mapping annotations, request-body conversion, response handling, and integration with validation and persistence technologies. By choosing methods correctly, returning appropriate HTTP status codes, validating input, and securing endpoints, developers can build reliable and maintainable web services.
Learn Advanced Java with JustAcademy
Build practical skills in Java, Spring Boot, REST APIs, and backend development through structured learning resources.
Explore Advanced Java Training
Register for a Course Demo
Visit JustAcademy Official Website