Pathubs Logo Mark
PATHUBSFREE CAREER ROADMAPS
HomeExploreDiscoverCompare ⚖️My Progress 📊Support
Student Support & Feedback

Have Questions or Need Help?

Have questions, feedback, or suggestions for new roadmaps and interactive tools? Reach out to our team — we review every message to make practical learning better for everyone.

supportpathubs@gmail.com Official Telegram Support (@PathubsSupport)
Pathubs

100% Free, Zero-Paywall Tech Career Roadmaps, In-Depth Practical Content, and Live Interactive Virtual Labs for Learners Worldwide.

Popular Careers

  • Frontend Development
  • Backend Development
  • AI & LLM Engineering
  • Full Stack Web Dev
  • Data Analytics

Platform Tools

  • Career Discovery Quiz
  • Compare Careers

Contact & Info

  • About Us
  • supportpathubs@gmail.com
  • Support Pathubs

© 2026 Pathubs. All Rights Reserved. Structured learning, practical content, and hands-on practice for learners worldwide.

AboutPrivacy PolicyTerms & ConditionsSitemapRobots
HomeBackend CareerHTTP Methods & Status Codes
API Protocol SemanticsIETF RFC 9110 StandardsBackend Contract Design

HTTP Methods & Status Codes — The API Communication Contract

Every backend API interaction is defined by a pair: an action intent (the HTTP method) and a standardized result (the HTTP status code). Master the safety and idempotency rules governing GET, POST, PUT, PATCH, and DELETE, navigate all 5 status code classes, resolve commonly confused codes, and test live contracts in an interactive API playground.

Category: Web & Backend Fundamentals
Prerequisites: HTTP Basics, Client-Server Architecture
Standard: IETF RFC 9110 (HTTP Semantics)
Focus: Safe & Idempotent API Design
Curriculum Outline7 Comprehensive Learning Sections
01Core Concept: The Universal API Contract02HTTP Methods: Safety & Idempotency03Status Codes: 5 Classes & Key Codes04Interactive HTTP / API Playground🔥 LAB05Debugging API Contract Failures🔥 DEBUG06Full Stack Connection: fetch() to DB07Mini Challenge: Design the Contract🎯 CHALLENGE

1. Core Concept: The Universal API Contract

How HTTP methods and status codes establish a predictable language between client and server.

When a frontend, mobile app, or terminal communicates with a backend API, it does not send random commands. Instead, it structures communication using standard HTTP requests and receives standard HTTP responses.

Every API interaction is composed of four fundamental elements:

  • HTTP Method (The Verb / Intent): Tells the server what kind of action the client wishes to perform (e.g., “Retrieve data”, “Create a record”, “Delete a resource”).
  • Target URL / URI (The Noun / Resource): Identifies what entity is being addressed (e.g., /api/courses or /api/courses/42).
  • Request Data / Headers (The Context): Carries metadata (authentication tokens, content types) and payload representations (JSON bodies).
  • HTTP Status Code (The Outcome): A 3-digit numerical code returned by the server telling the client what actually happened (e.g., “Success”, “Client mistake”, “Server crash”).
Real-World API Contract Example:
GET /api/courses/42
→ 200 OK: Server retrieved course #42 and returns its JSON body.

POST /api/courses (with body: { "title": "Docker Basics" })
→ 201 Created: Server validated data, inserted new course #105, and returned Location: /api/courses/105.
Backend Developer Perspective:

A backend engineer does not just “write functions”. You design an API contract. If your backend returns 200 OK with an error message inside the body (e.g. { "error": "password too short" }), the browser's response.ok will evaluate to true! Proper status codes ensure that HTTP caching proxies, browsers, SDKs, and frontend error handlers work seamlessly without manual guessing.

2. HTTP Methods: Semantics, Safety & Idempotency

Mastering the 5 primary REST methods under IETF RFC 9110 specifications.

Under IETF RFC 9110 (HTTP Semantics), methods are defined by two critical formal properties:

  • Safe Methods: A method is safe if its primary purpose is retrieval and it does not alter the state of the origin server. Browsers and search crawlers (like Googlebot) can call safe methods repeatedly without fear of modifying data.
  • Idempotent Methods: A method is idempotent if the intended effect on the server of multiple identical requests is the exact same as a single request. If a mobile connection drops mid-flight, an idempotent request can be retried safely without duplicating records.
MethodIntended ActionSafe?Idempotent?Carries Body?Typical Backend Use
GETRetrieve resource representationYESYESNo (ignored)Read records from database, cacheable
POSTCreate subordinate resource / process payloadNONOYESInsert new records, execute payment transactions
PUTCompletely replace target resource or create at URINOYESYESOverwrite entire document/record; repeated calls produce same state
PATCHApply partial delta modification to resourceNONO (by RFC spec)YESUpdate 1 or 2 fields (e.g. change status to “published”)
DELETERemove target resourceNOYESNo (uncommon)Delete row from database; deleting an already deleted item leaves state empty
PUTvsPATCH
  • PUT (Full Replacement): Replaces the entire resource. If a course has title, price, and category, and PUT sends only { "title": "New" }, the price and category are reset or wiped!
  • PATCH (Partial Delta): Only modifies specified fields. If PATCH sends { "price": 1999 }, title and category remain completely untouched.
POSTvsPUT
  • POST (Non-Idempotent Create): Client posts to a collection URI (/api/courses). The server creates a brand new ID. Calling it 5 times creates 5 separate database rows.
  • PUT (Idempotent Replace): Client targets a specific resource URI (/api/courses/42). Calling it 5 times leaves the exact same single record with the exact same values.

3. HTTP Status Codes: The 5 Classes & Key Codes

Navigating status code families and resolving commonly confused codes in full-stack engineering.

HTTP status codes are 3-digit integers categorized into 5 distinct classes based on their first digit:

1xxInfo

Informational: Request received, process continuing (e.g. 100 Continue, 101 Switching Protocols).

2xxSuccess

Successful: The action was received, understood, and accepted (200 OK, 201 Created, 204 No Content).

3xxRedirect

Redirection: Further action must be taken to complete request (301 Permanent, 302 Found, 304 Not Modified).

4xxClient Error

Client Error: Bad syntax, invalid data, or unauthorized (400, 401, 403, 404, 405, 409, 422, 429).

5xxServer Error

Server Error: The server failed to fulfill an apparently valid request (500, 502, 503).

Resolving Frequently Confused Status Codes

400 Bad Requestvs422 Unprocessable Content
  • 400 Bad Request: The server cannot parse the request due to malformed syntax (broken JSON, invalid URL encoding, corrupted HTTP headers).
  • 422 Unprocessable Content: The JSON syntax is completely valid, but the payload fails domain validation rules (e.g. price: -50 or missing required email field). Standardized in RFC 9110; default in frameworks like FastAPI.
401 Unauthorizedvs403 Forbidden
  • 401 Unauthorized (Unauthenticated): The user has not provided credentials or the token is invalid/expired. Must return a WWW-Authenticate header.
  • 403 Forbidden (Unauthorized): The user is authenticated and identity is known, but does not have permission to access the resource (e.g. regular student attempting to delete a course).
404 Not Foundvs405 Method Not Allowed
  • 404 Not Found: The URL path itself does not match any route or database record.
  • 405 Method Not Allowed: The resource exists at that URL, but does not support that HTTP verb (e.g. DELETE /api/courses). Must include an Allow header.
500 Internal Errorvs502 Bad Gatewayvs503 Service Unavail
  • 500: An unhandled exception or crash occurred inside the application code.
  • 502: A reverse proxy/gateway (Nginx, Cloudflare) could not connect to the upstream Node/Python process.
  • 503: The server is temporarily overloaded or undergoing scheduled maintenance.
Framework Conventions Note:

While RFC 9110 specifies semantic standards, framework conventions can differ: Express APIs frequently return400 Bad Requestfor schema validation errors, whereas Python's FastAPI and Ruby on Rails default to 422 Unprocessable Content for Pydantic/ActiveRecord validation errors. Both are accepted production practices.

4. Interactive HTTP / API Playground

Dispatch requests across simulated RESTful resources and inspect status codes, headers, and bodies.

Use the interactive API workbench below to experiment with HTTP methods and endpoints. Click any of the quick presets or customize the method, URL, and JSON request body to observe how the backend responds.

Presets:
Request Body (JSON)Body Not Recommended
Backend Response InspectorAwaiting Request
Select a preset above or click Send Request to inspect the simulated HTTP response.

5. Debugging API Contract Failures

Identify and fix realistic method and status-code anti-patterns seen in broken backends.

A backend API that returns incorrect HTTP methods or misleading status codes breaks frontend error handlers, caches corrupted data, and creates security vulnerabilities. Analyze each of the 6 realistic failure scenarios below and select the proper architectural fix.

Scenario 1: Using GET for Resource Creation

SEMANTIC VIOLATION

A developer creates an endpoint `GET /api/courses/create?title=Microservices` that inserts a row into the database whenever a user navigates to it.

// Broken Express Handler
app.get("/api/courses/create", async (req, res) => {
  const course = await db.courses.create({ title: req.query.title });
  res.json(course);
});
Select the correct architectural fix:
Keep GET but add a secret query parameter ?secret=admin to authorize the creation.
Change the HTTP method to POST /api/courses, receive data in the request body, and return status 201 Created.
Change the method to PUT /api/courses/create and return status 200 OK.

6. Full Stack Connection: From Frontend fetch() to DB

How HTTP methods map to database operations, and how frontend code reliably handles status codes.

In a complete Full Stack application, HTTP methods and status codes serve as the universal bridge connecting frontend UI events to backend database queries:

HTTP MethodCRUD OperationSQL OperationTypical Success StatusTypical Error Statuses
GETReadSELECT200 OK404 Not Found, 401
POSTCreateINSERT201 Created400, 422, 409 Conflict
PUTReplaceUPDATE (all columns)200 OK400, 404, 422
PATCHPartially UpdateUPDATE (target columns)200 OK400, 404, 422
DELETEDeleteDELETE204 No Content404, 403 Forbidden
Frontend fetch() Status Handling Patternclient/apiClient.js
async function updateCoursePrice(courseId, newPrice) {
  const response = await fetch(`/api/courses/${courseId}`, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${getToken()}`
    },
    body: JSON.stringify({ price: newPrice })
  });

  // 1. response.ok evaluates to true ONLY for 200-299 status codes
  if (!response.ok) {
    if (response.status === 401) {
      redirectToLogin();
      return;
    }
    if (response.status === 403) {
      showToast("Access Denied: You do not have permission to edit prices.");
      return;
    }
    if (response.status === 422) {
      const errorData = await response.json();
      displayFormErrors(errorData.field, errorData.message);
      return;
    }
    throw new Error(`Server error: ${response.status}`);
  }

  // 2. Parse successful representation
  const updatedCourse = await response.json();
  return updatedCourse;
}

7. Mini Challenge: Design the API Contract & Recap

Design the correct HTTP method and status code for 8 real-world backend API operations.

API Contract Design Challenge

1. Fetch details for course #42
2. Register a brand new user account
3. Update only the price of course #42
4. Delete course #42 with zero body bytes returned
5. Request course ID #999 which does not exist in DB
6. Submit form with invalid negative price
7. Access protected admin metrics with no auth token
8. Logged-in student tries to delete course #42
Method Semantics

GET is safe and idempotent. PUT and DELETE are idempotent. POST and PATCH are non-idempotent.

Status Families

2xx for Success, 3xx for Redirection/Caching, 4xx for Client Errors, and 5xx for Server Crashes.

Golden Rule

Never return 200 for failures, never return 500 for invalid user input, and use 403 when identity is known but forbidden.