HTTP Basics : The Language of REST


HTTP Basics : The Language of REST

Quick Summary

HTTP (HyperText Transfer Protocol) is the basic language of the web and the foundation of most REST APIs. Every time your browser or mobile app talks to a server, it is sending HTTP requests and receiving HTTP responses.

HTTP methods such as GET, POST, PUT, PATCH, and DELETE act like verbs that describe what you want to do with a resource: read it, create it, update it, or remove it.

Status codes (200, 201, 400, 401, 403, 404, 409, 500, and others) are short numeric messages from the server that tell you whether the request succeeded or failed, and why.

Each request is made up of headers, an optional body, and sometimes a query string. Understanding the difference between these parts is essential for designing and debugging REST APIs.

Table of Contents


Key Points

  • HTTP is a request–response protocol: a client sends a request, and a server returns a response describing the result.
  • GET, POST, PUT, PATCH, and DELETE are the main HTTP methods used in REST to represent read, create, update, and delete operations on resources.
  • Status codes are grouped by their first digit (2xx success, 4xx client errors, 5xx server errors) and give you a quick signal of what went wrong.
  • Headers carry metadata (such as content type and authentication), the body carries the main data payload, and the query string is used for filtering, searching, and pagination.
  • By combining the right method, URL, headers, and body, you can model almost any business operation as a clean RESTful API call.

Detailed Explanation

1. HTTP Methods: The Verbs of REST

In REST, resources are usually represented as nouns in URLs (for example, /users, /orders, /products). HTTP methods then act as verbs that describe the action on those resources.

Below is a high-level view of the five most common methods:

  • GET: Read or retrieve data. GET should not change data on the server.
  • POST: Create a new resource or trigger a non-idempotent operation (for example, place an order).
  • PUT: Fully replace an existing resource at a specific URL. If some fields are missing, they may be overwritten or cleared.
  • PATCH: Partially update an existing resource. Only the fields you send are changed.
  • DELETE: Remove a resource.

When you design or use a REST API, choosing the correct method makes your API intuitive and easier to maintain. For example, using POST for everything technically works, but it hides the intent of each operation and breaks common expectations.

2. Understanding Common HTTP Status Codes

Every HTTP response includes a status code. It is a three-digit number where the first digit indicates the category:

  • 1xx: Informational (rarely used directly in APIs)
  • 2xx: Success (the request was handled correctly)
  • 3xx: Redirection (the resource moved somewhere else)
  • 4xx: Client error (the request was incorrect or unauthorized)
  • 5xx: Server error (the server failed while processing a valid request)

In day-to-day REST API work, you will mainly see and use the following codes:

  • 200 OK: The request succeeded, and the response body usually contains the requested data.
  • 201 Created: A new resource was successfully created, often with a Location header pointing to the new URL.
  • 400 Bad Request: The server could not understand the request (invalid JSON, missing required fields, etc.).
  • 401 Unauthorized: Authentication is required or the token is invalid. The client must log in or send valid credentials.
  • 403 Forbidden: The client is authenticated but does not have permission to perform this action.
  • 404 Not Found: The server could not find the requested resource. The URL may be wrong, or the resource does not exist.
  • 409 Conflict: The request conflicts with the current state of the resource (for example, duplicate data or version conflict).
  • 500 Internal Server Error: A generic server-side error. The request might be valid, but the server crashed or encountered an unexpected condition.

Learning to “read” these status codes quickly will help you debug issues much faster. For example, if you see 400, you first check the request body; if you see 401 or 403, you check authentication and permissions.

3. Request Structure: Headers, Body, and Query String

An HTTP request can be divided into three main parts that you will encounter in every REST call:

  • Headers: Key–value pairs with metadata about the request. Examples: Content-Type: application/json, Authorization: Bearer <token>, Accept: application/json.
  • Body: The main data payload of the request. It is usually used in POST, PUT, and PATCH to send JSON data to the server.
  • Query string: A list of key–value pairs appended to the URL after ?, often used for filters, sorting, pagination, or search (for example, /users?role=admin&page=2).

A simple rule of thumb is: if the information changes which resource you are targeting, it usually belongs in the path or query string. If it is content you want to send as data, it goes into the body. If it is metadata about how to process the request, it belongs in headers.

Comparison Table

The following table summarizes the main HTTP methods, their typical usage, and example status codes you might expect in a REST API.

Method Main purpose Typical success codes Idempotent Safe (no data change) Typical examples
GET Read a resource or list of resources 200 Yes Yes Get user list, search products, read profile details
POST Create a new resource or trigger an action 201, 200 No No Sign up a user, submit an order, start a background job
PUT Completely replace a resource at a given URL 200, 204 Yes No Replace user profile, overwrite settings document
PATCH Partially update a resource 200, 204 Usually yes (depends on implementation) No Change password, update status field, modify a few columns
DELETE Remove a resource 200, 204 Yes No Delete user account, cancel order, remove file

Practice: HTTP Request Examples by Method

In this section, we will create simple request examples for each method against a hypothetical REST API at https://api.example.com. You can try these commands in a terminal using curl, or adapt them in your favorite HTTP client such as Postman or Insomnia.

1) GET example: Read a list of users

curl -X GET "https://api.example.com/users?role=admin&page=1" \
  -H "Accept: application/json"

This GET request asks the server for the first page of users whose role is admin. The method is GET, the query string carries filter and pagination parameters, and the Accept header indicates that the client expects JSON. If it succeeds, you usually receive a 200 OK status with a JSON array of users.

2) POST example: Create a new user

curl -X POST "https://api.example.com/users" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "email": "alice@example.com",
    "name": "Alice",
    "role": "admin"
  }'

This POST request creates a new user. The JSON body carries the data, and Content-Type: application/json tells the server how to parse it. A successful creation usually returns 201 Created and might include a Location header such as /users/123.

3) PUT example: Replace a user profile

curl -X PUT "https://api.example.com/users/123" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "email": "alice@example.com",
    "name": "Alice Cooper",
    "role": "editor"
  }'

The PUT request replaces the user with ID 123 using the full JSON document provided in the body. Any fields not included may be overwritten or removed depending on the API design. A successful update usually returns 200 OK or 204 No Content.

4) PATCH example: Partially update a user

curl -X PATCH "https://api.example.com/users/123" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "role": "viewer"
  }'

This PATCH request only changes the role field of user 123. All other fields stay the same. APIs often return 200 OK with the updated resource or 204 No Content with an empty body.

5) DELETE example: Remove a user

curl -X DELETE "https://api.example.com/users/123" \
  -H "Accept: application/json"

This DELETE request removes user 123. Many APIs return 204 No Content when the deletion is successful. If the user does not exist, you might receive 404 Not Found. If the account is protected, you might get 403 Forbidden.


Step-by-Step Practice Plan

  1. Install a REST client or use curl
    Install a tool such as Postman, Insomnia, or HTTPie, or use curl in your terminal. Being comfortable with at least one HTTP client helps you experiment quickly with real APIs.
  2. Pick an open test API
    Search for a public REST API that does not require authentication (for example, a public JSON placeholder or sample API). Confirm the base URL and available endpoints from the documentation.
  3. Practice each HTTP method
    Start by sending GET requests to list and read resources. Then practice creating resources with POST, and updating them with PUT and PATCH. Finally, try deleting resources with DELETE. Observe how the status codes and response bodies change.
  4. Experiment with headers, body, and query string
    Change headers such as Accept and Content-Type, add or remove query parameters, and modify JSON bodies. Notice when the server returns 400, 401, 403, or 404 and use those signals to guess what went wrong.
  5. Inspect raw requests and responses
    Use your client’s “raw view” or developer tools in the browser to inspect the exact HTTP message. Pay attention to the request line, headers, body, and the status code in the response.
  6. Summarize patterns you see
    After some practice, write down your own summary of when each method is used, what typical status codes appear, and how headers, bodies, and query strings work together. This personal cheat sheet will help you when designing or debugging real APIs.

Additional Things to Think About

  • Authentication and authorization: Once you are comfortable with basic methods and status codes, study common authentication schemes such as API keys, JWT, and OAuth 2.0, and how they are carried in headers.
  • Error handling: Good APIs return structured error responses (for example, JSON with an error_code and message) together with meaningful status codes. Plan a consistent error format for your own APIs.
  • Versioning and compatibility: Over time, APIs evolve. Decide how you will version your API (for example, /v1, /v2) while keeping backward compatibility for existing clients.
Reactions

댓글 쓰기

0 댓글