REST APIs

MEDIUM3 min readby AdminJune 20, 2026History
0.0|0 ratingsLog in to rate

REST (Representational State Transfer) is an architectural style for designing networked applications. It utilizes a stateless client-server model where web res...

#ai-engineering#course#rest

Definition

REST (Representational State Transfer) is an architectural style for designing networked applications. It utilizes a stateless client-server model where web resources are identified by URI paths and manipulated using standard HTTP operations.

Why It Exists

Integrating heterogeneous systems (e.g., a React Native frontend, a Python orchestration microservice, and external LLM nodes) requires a uniform, standard protocol. REST provides this framework-agnostic communication standard, making it simple to scale, debug, and cache responses.

How It Works

python
1
2
3
4
5
6
7
8
9
10
REST ARCHITECTURAL FLOW
 ┌────────┐
 │ Client │ ───[ URI: /api/v1/sessions/123/messages ]───► ┌────────┐
 └────────┘                                               │ Server │
  - Stateless Request: Must contain all credentials       └────────┘
  - Identifies "Message Resources" under Session 123

1. **Client-Server Separation**: The client (UI) and server (data logic) are decoupled and can evolve independently.
2. **Statelessness**: Every request from client to server must contain all the information necessary to understand and complete the request (e.g., authorization token). The server does not store session context in its local active thread memory.
3. **Resource Identification**: Resources are identified by logical URIs (e.g., `/api/v1/chats`).

Real-World Example

Example

In Gemini API or OpenAI API, conversations are mapped as resources. You send requests to endpoints like /v1/chat/completions or /v1/models. The server returns responses represented as JSON structures, containing no local session context unless explicitly passed in the parameters.

Python Example

Example

Here is a simulation of a REST resource routing layer mapping resource paths to actions:

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from typing import Dict, Any, Optional

class MockRESTServer:
    """Simulates a stateless REST routing layer for managing chats."""
    def __init__(self):
        # Database mock
        self.db: Dict[str, Dict[str, Any]] = {
            "chat_1": {"user": "Alice", "messages": ["Hello"]},
            "chat_2": {"user": "Bob", "messages": ["Hi"]}
        }

    def route_request(self, method: str, path: str, payload: Optional[dict] = None) -> Dict[str, Any]:
        path_parts = path.strip("/").split("/")
        
        # Mapping GET /chats/{chat_id}
        if method == "GET" and len(path_parts) == 2 and path_parts[0] == "chats":
            chat_id = path_parts[1]
            if chat_id in self.db:
                return {"status_code": 200, "data": self.db[chat_id]}
            return {"status_code": 404, "error": "Chat session not found."}
            
        # Mapping POST /chats
        if method == "POST" and len(path_parts) == 1 and path_parts[0] == "chats":
            if not payload or "user" not in payload:
                return {"status_code": 400, "error": "Invalid payload."}
            new_id = f"chat_{len(self.db) + 1}"
            self.db[new_id] = {"user": payload["user"], "messages": []}
            return {"status_code": 201, "chat_id": new_id}
            
        return {"status_code": 405, "error": "Method Not Allowed."}

# Test execution
if __name__ == "__main__":
    server = MockRESTServer()
    print("Fetch chat_1:", server.route_request("GET", "/chats/chat_1"))
    print("Create chat:", server.route_request("POST", "/chats", {"user": "Charlie"}))

Interview Questions

  • Beginner: What does REST stand for?
  • Intermediate: What does it mean for an API to be "stateless"?
  • Advanced: How do we maintain conversational history in a RESTful AI product if the server-client interaction is strictly stateless?

Interview Answers

  • Beginner: REST stands for Representational State Transfer. It is a set of design principles for building APIs using standard HTTP protocol standards.
  • Intermediate: Statelessness means the server does not store any memory of past requests from the client. Every request must be self-contained, including all parameters, settings, and authorization tokens required for completion.
  • Advanced: We store conversational state (previous messages) in a database (like PostgreSQL or DynamoDB) keyed by a unique session_id. In each request, the client passes this session_id. The server retrieves the corresponding history from the database, builds the prompt context, executes the LLM call, saves the new message to the database, and returns the response.

Common Mistakes

  • Verbs in URI paths: Creating endpoints like /getChatHistory or /deleteUser. In REST, URIs represent nouns (resources). Use HTTP methods to represent actions instead: GET /chats/{id} and DELETE /users/{id}.

Assignment

Design a RESTful URI path structure for a system that manages Agent resources, their sub-resource Task items, and specific Execution history logs.


Discussion

Join the discussion! Sign in to leave comments and ask questions.

Loading discussion...