Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

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

MethodIntentCommon success
GETRead a resource200 OK
POSTCreate or trigger work201 Created or 202 Accepted
PUTReplace a resource200 OK or 204 No Content
PATCHPartially update200 OK or 204 No Content
DELETERemove a resource204 No Content
Status rangeMeaningExample
2xxSuccessful200, 201, 204
3xxRedirect or cache behavior304
4xxClient request problem400, 401, 404
5xxServer or dependency failure500, 503

Common Mistake and Practices

Common Mistake: Returning 200 OK with 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 400 for malformed input and 404 for missing resources.
  • Include a useful Location header 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

Quick Knowledge Test

Loading quiz questions...