Back to Study Material Python

REST API

A REST (Representational State Transfer) API is a web service that exposes data and operations over HTTP using standard conventions. REST APIs are the back...

REST API

Designing REST APIs in Python

A REST (Representational State Transfer) API is a web service that exposes data and operations over HTTP using standard conventions. REST APIs are the backbone of modern web and mobile applications, allowing frontends, mobile apps, and third-party services to communicate with your backend.

REST principles every developer must know:

1. Resources are identified by URLs (endpoints): /api/users, /api/products/42, /api/orders. 2. HTTP methods define actions: GET (read), POST (create), PUT (full update), PATCH (partial update), DELETE (remove). 3. Stateless: each request carries all the information needed; the server stores no client session state. 4. Responses use standard formats (JSON) and HTTP status codes.

Designing clean REST endpoints: GET /api/articles --> list all articles POST /api/articles --> create a new article GET /api/articles/5 --> retrieve article with id=5 PUT /api/articles/5 --> replace article 5 entirely PATCH /api/articles/5 --> partially update article 5 DELETE /api/articles/5 --> delete article 5

Status codes in REST responses: 200 OK - successful GET, PUT, PATCH 201 Created - successful POST (include Location header with new resource URL) 204 No Content - successful DELETE 400 Bad Request - invalid input (include error details in body) 401 Unauthorized - missing or invalid authentication 403 Forbidden - authenticated but not allowed 404 Not Found - resource does not exist 409 Conflict - duplicate resource (e.g., email already registered) 422 Unprocessable Entity - validation failed 500 Internal Server Error - unexpected server error

JSON response structure should be consistent: { "status": "success", "data": { "id": 5, "title": "REST API Guide" }, "message": null }

Authentication options: JWT tokens (stateless, good for SPAs and mobile), OAuth2 (for third-party access), or API keys (for server-to-server).

Versioning your API prevents breaking changes for existing clients: /api/v1/articles.

Practical tip: Always paginate list endpoints. Returning thousands of records in one response crashes clients and servers. Use limit/offset or cursor-based pagination and include next/previous links in the response.

Exam tip: PUT is idempotent (calling it multiple times produces the same result); POST is not. This distinction is commonly tested and matters for caching and retry logic in distributed systems.