APIs · Lesson 2
HTTP Methods and Status Codes
HTTP as an API Contract
HTTP methods and status codes communicate intent between an API and its clients. Methods describe the requested operation, while status codes describe the result. Consistent use makes APIs easier to integrate, debug, and secure.
Returning a Status Code
A controller should choose the response code that matches the outcome rather than returning 200 OK for every path. The following Java example models a small decision made by an API service.
public class ApiResponsePolicy {
public int statusForLookup(boolean resourceFound) {
return resourceFound ? 200 : 404;
}
public static void main(String[] arguments) {
ApiResponsePolicy policy = new ApiResponsePolicy();
System.out.println(policy.statusForLookup(true));
System.out.println(policy.statusForLookup(false));
}
}
Method and Status Comparison
| Method | Intent | Common success |
|---|---|---|
| GET | Read a resource | 200 OK |
| POST | Create or trigger work | 201 Created or 202 Accepted |
| PUT | Replace a resource | 200 OK or 204 No Content |
| PATCH | Partially update | 200 OK or 204 No Content |
| DELETE | Remove a resource | 204 No Content |
| Status range | Meaning | Example |
|---|---|---|
| 2xx | Successful | 200, 201, 204 |
| 3xx | Redirect or cache behavior | 304 |
| 4xx | Client request problem | 400, 401, 404 |
| 5xx | Server or dependency failure | 500, 503 |
Common Mistake and Practices
Common Mistake: Returning
200 OKwith an error message in the body for invalid input. Clients and monitoring tools then misclassify a failed operation as successful.
- Use idempotent methods consistently.
- Return
400for malformed input and404for missing resources. - Include a useful
Locationheader after creation. - Document error response shapes.
- Never expose stack traces in API responses.
Real-World Use Case
A course API returns 201 Created when a learner enrolls, 409 Conflict when an enrollment already exists, and 404 Not Found when the course identifier is unknown.
Quiz Check