HTTP REST API Notes

REST stands for REpresentational State Transfer, an architectural style used in web services for communication between a client and a server over HTTP.

It follows a stateless, client-server communication model where operations on resources are performed via HTTP methods.

Key Principles of REST:

  1. Stateless: Each request from the client to the server must contain all the information needed to understand and process the request. The server does not store any client state between requests.
  2. Client-Server: Separation between the client (frontend) and the server (backend) to enable independent development and scaling.
  3. Uniform Interface: Consistent and well-defined interface across the system (usually using HTTP verbs).
  4. Resource-Based: Operations in REST are performed on resources, which are typically represented in a structured format like JSON or XML.
  5. Cacheable: Responses should be defined as cacheable or not to improve performance.
  6. Layered System: The API should work even if there are intermediaries like load balancers or proxies between the client and server.

HTTP Methods in REST API

These are also called HTTP verbs or actions.

  1. GET:
    • Retrieves data from the server.
    • Idempotent: No matter how many times you call it, the result remains the same.
    • Example: Get a list of users or retrieve a specific user.
  2. POST:
    • Sends data to the server to create a new resource.
    • Non-idempotent: Each call can result in a different resource being created.
    • Example: Create a new user.
  3. PUT:
    • Updates an existing resource or creates a resource if it doesn’t exist.
    • Idempotent: Multiple calls will produce the same result.
    • Example: Update a user’s details.
  4. PATCH:
    • Partially updates an existing resource.
    • Idempotent: Only specific fields are updated without affecting the entire resource.
    • Example: Update a single attribute of a user.
  5. DELETE:
    • Deletes a specified resource from the server.
    • Idempotent: Deleting a resource that doesn’t exist returns the same result.
    • Example: Delete a user.

HTTP Status Codes

Every HTTP request returns a status code along with the response.

  1. 2xx – Success:
    • 200 OK: The request was successful (e.g., for GET, PUT).
    • 201 Created: The resource was successfully created (e.g., for POST).
    • 204 No Content: The request was successful, but no data was returned (e.g., for DELETE).
  2. 3xx – Redirection:
    • 301 Moved Permanently: The resource has been permanently moved to a new URL.
    • 304 Not Modified: No change in resource; cached resource can be used.
  3. 4xx – Client Error:
    • 400 Bad Request: The server could not understand the request due to invalid syntax.
    • 401 Unauthorized: Authentication is required and has failed or hasn’t been provided.
    • 403 Forbidden: The client does not have access rights to the resource.
    • 404 Not Found: The server cannot find the requested resource.
  4. 5xx – Server Error:
    • 500 Internal Server Error: The server encountered an unexpected condition.
    • 502 Bad Gateway: Invalid response received from the upstream server.
    • 503 Service Unavailable: The server is not ready to handle the request (e.g., maintenance).

Key Components of a REST API

  1. Endpoint (URL):
    • The unique URL used to access a resource.
    • Follows the format: http(s)://<server>/<resource>/<identifier>
    • Example: /users/123
  2. Resource:
    • The entity (data object) that a REST API exposes.
    • Each resource has its unique identifier (often part of the URL).
    • Example: /users/123 (user with ID 123).
  3. Headers:
    • Provide additional information in the request or response.
    • Common headers:
      • Content-Type: Specifies the media type (e.g., application/json).
      • Authorization: Sends credentials for accessing protected resources.
      • Accept: Informs the server about the types of data the client can process.
  4. Payload (Body):
    • The data sent in the request or response (typically in POST, PUT, and PATCH methods).
    • The payload is usually in JSON or XML format.

Authentication in REST API

  1. Basic Authentication:
    • Encodes username and password in base64 and sends in the Authorization header.
    • Header Example:
      Authorization: Basic <base64encoded_credentials>
  2. Token-Based Authentication (JWT):
    • After logging in, the server generates a token (JWT) which the client uses in subsequent requests.
    • Header Example:
      Authorization: Bearer <token>
  3. OAuth:
    • An open-standard protocol for authorization.
    • Used to allow third-party services to access user data without exposing credentials.

Common REST API Tools

  1. cURL:
    • A command-line tool used to send HTTP requests.
    • Example:
      curl -X GET "http://example.com/users"
  2. Postman:
    • A popular API testing tool with a user-friendly interface.
    • Allows sending requests, creating test suites, and visualizing API responses.

Best Practices for REST API Design

  1. Use Proper HTTP Methods: Ensure the right method is used for the operation (e.g., GET for reading, POST for creating).
  2. Meaningful Status Codes: Return appropriate HTTP status codes for different scenarios (e.g., 404 for not found).
  3. Statelessness: Do not rely on server-side sessions; every request should contain all necessary information.
  4. Pagination: For large datasets, implement pagination to avoid returning too much data at once.
    • Example: /users?page=2&limit=50.
  5. Versioning: Use versioning in the API URL to maintain backward compatibility.
    • Example: /v1/users.
  6. Secure Endpoints: Always secure sensitive endpoints with authentication mechanisms like OAuth or token-based systems.
    • Use HTTPS to encrypt data transmission.