โ† Back | REST API Design
Week 2โ€“3
Week 2โ€“3 ยท Core Backend

REST API Design

REST is the standard way for systems to communicate over HTTP. Every mobile app, frontend, and microservice talks to a backend through REST APIs. This is the skill that gets you hired.

๐Ÿ”— HTTP Methods ๐Ÿ“Š Status Codes ๐Ÿงช Postman Testing
๐Ÿง 
Concept
What is REST?
REST is like a restaurant menu. The menu defines what you can order (endpoints), how to order (HTTP methods), and what you'll get back (response format). The kitchen (server) doesn't care if you're a customer from India or Japan โ€” anyone who follows the menu protocol gets food.

REST (Representational State Transfer) is an architectural style for building web APIs. A REST API uses HTTP protocol and follows these constraints:

  • Client-Server โ€” frontend and backend are separate. Frontend calls API, doesn't know how backend works.
  • Stateless โ€” each request contains all the information needed. Server doesn't remember previous requests. (No sessions by default.)
  • Uniform Interface โ€” standard HTTP methods (GET, POST, PUT, DELETE) and standard formats (JSON).
  • Resource-based URLs โ€” URLs represent things (nouns), not actions (verbs).
๐Ÿ“ก
Core Concept
HTTP Methods (Verbs)
GET

Read data. Never changes state. Safe and idempotent.

POST

Create new resource. Not idempotent.

PUT

Replace entire resource. Idempotent.

PATCH

Update part of a resource.

DELETE

Remove a resource. Idempotent.

ActionHTTP MethodURLRequest Body
Get all studentsGET/api/studentsNone
Get one studentGET/api/students/1None
Create studentPOST/api/studentsJSON student data
Replace studentPUT/api/students/1Complete JSON
Update email onlyPATCH/api/students/1Only changed fields
Delete studentDELETE/api/students/1None
Idempotent means calling it multiple times has the same result as calling it once. DELETE /students/1 twice = student 1 is deleted (same result). POST /students twice = two students created (not idempotent).
๐Ÿ“Š
Must Know
HTTP Status Codes
CodeNameWhen to use
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST (resource created)
204No ContentSuccessful DELETE (nothing to return)
400Bad RequestInvalid request data (validation failed)
401UnauthorizedNot authenticated (no/invalid token)
403ForbiddenAuthenticated but not allowed
404Not FoundResource doesn't exist
409ConflictDuplicate resource (email already exists)
500Internal Server ErrorUnexpected server error (bug)
Memory trick: 2xx = Success, 3xx = Redirect, 4xx = Client's fault, 5xx = Server's fault.
๐Ÿ”—
Best Practice
RESTful URL Design

Rules for clean REST URLs

โŒ Bad (don't do)โœ… Good (do this)
/getStudents/students
/createStudentPOST /students
/deleteStudent/1DELETE /students/1
/students/getEnrolledCourses/1/students/1/courses
/Students (uppercase)/students (lowercase)
/student_data (underscores)/students (hyphens if needed)
# Nested resources โ€” clear hierarchy GET /courses โ†’ All courses GET /courses/5 โ†’ Course with id=5 GET /courses/5/students โ†’ All students in course 5 POST /courses/5/students โ†’ Enroll a student in course 5 GET /courses/5/students/12 โ†’ Student 12 in course 5 # Filtering and pagination โ€” use query params GET /students?city=Pune โ†’ Filter by city GET /students?page=2&size=10 โ†’ Pagination GET /students?sort=name&dir=asc โ†’ Sorting
๐ŸŒฑ
Code
Full REST Controller in Spring Boot
@RestController @RequestMapping("/api/students") public class StudentController { private final StudentService service; public StudentController(StudentService service) { this.service = service; } // GET /api/students @GetMapping public ResponseEntity<List<Student>> getAll() { return ResponseEntity.ok(service.findAll()); } // GET /api/students/1 @GetMapping("/{id}") public ResponseEntity<Student> getById(@PathVariable Long id) { return ResponseEntity.ok(service.findById(id)); } // POST /api/students (body: JSON) @PostMapping public ResponseEntity<Student> create(@RequestBody @Valid Student student) { Student saved = service.save(student); return ResponseEntity.status(HttpStatus.CREATED).body(saved); } // PUT /api/students/1 (full update) @PutMapping("/{id}") public ResponseEntity<Student> update( @PathVariable Long id, @RequestBody Student student) { return ResponseEntity.ok(service.update(id, student)); } // DELETE /api/students/1 @DeleteMapping("/{id}") public ResponseEntity<Void> delete(@PathVariable Long id) { service.delete(id); return ResponseEntity.noContent().build(); } // GET /api/students/search?city=Pune @GetMapping("/search") public List<Student> search(@RequestParam String city) { return service.findByCity(city); } }
โš ๏ธ
Best Practice
Global Error Handling
// Custom exception public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } } // Global exception handler โ€” catches exceptions from ALL controllers @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public Map<String, String> handleNotFound(ResourceNotFoundException ex) { return Map.of("error", ex.getMessage(), "status", "404"); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Map<String, String> handleGeneral(Exception ex) { return Map.of("error", "Something went wrong"); } }
When a student isn't found, throw new ResourceNotFoundException("Student not found with id: " + id) and Spring will automatically return a 404 JSON response.
๐Ÿงช
Tool
Testing with Postman

Postman is the standard tool for testing REST APIs. Download it from postman.com.

1

GET all students

Method: GET ยท URL: http://localhost:8080/api/students ยท Click Send

2

POST create student

Method: POST ยท URL: http://localhost:8080/api/students
Headers: Content-Type: application/json
Body (raw JSON):

{"name": "Rahul Sharma", "email": "rahul@email.com", "city": "Pune"}
3

GET student by id

Method: GET ยท URL: http://localhost:8080/api/students/1

4

DELETE student

Method: DELETE ยท URL: http://localhost:8080/api/students/1 ยท Expect 204 No Content

๐ŸŽฏ
Interview Prep
Common Interview Questions
QWhat is REST? What are its key principles?

REST (Representational State Transfer) is an architectural style for distributed hypermedia systems. Key principles: Stateless (no session state on server), Client-Server (separation of concerns), Uniform Interface (HTTP methods + status codes), Cacheable (responses can be cached), Layered System (client doesn't know if it's talking to the actual server or a proxy).

QWhat is the difference between PUT and PATCH?

PUT replaces the entire resource with the request body. If you omit a field, it's set to null/default. Idempotent.

PATCH applies a partial update โ€” only the fields provided in the request body are changed. Other fields remain untouched. Used when you want to update just one field (e.g., just the email) without sending the entire object.

QWhat are HTTP status codes? Give examples of 2xx, 4xx, 5xx.

2xx Success: 200 OK (request succeeded), 201 Created (resource created), 204 No Content (success, nothing to return โ€” DELETE).

4xx Client Error: 400 Bad Request (invalid input), 401 Unauthorized (not authenticated), 403 Forbidden (not authorised), 404 Not Found (resource doesn't exist), 409 Conflict (duplicate).

5xx Server Error: 500 Internal Server Error (unhandled exception), 503 Service Unavailable (server overloaded).

QWhat is ResponseEntity in Spring Boot?

ResponseEntity represents the entire HTTP response including status code, headers, and body. It gives you full control over the response.

Instead of just returning an object (which always gives 200), you can return ResponseEntity.status(201).body(savedStudent) or ResponseEntity.notFound().build().

QWhat is @RestControllerAdvice?

@RestControllerAdvice is used to define a global exception handler that applies to all controllers. You define @ExceptionHandler methods that intercept specific exceptions and return appropriate HTTP responses.

Without it, unhandled exceptions return a generic 500 error with a Spring whitepage. With it, you return clean JSON error responses with correct status codes.

QWhat is the difference between @PathVariable and @RequestParam?

@PathVariable extracts a value embedded in the URL path: /students/{id} โ†’ the id is part of the path structure.

@RequestParam extracts a query parameter from the URL: /students?city=Pune โ†’ city is a query param after the ?

Use PathVariable for identifying a specific resource. Use RequestParam for filtering, sorting, or pagination.