---
title: REST API Explained: HTTP Methods, Status Codes, Example
url: https://www.masaischool.com/resources/rest-api-explained
description: What an API and a REST API are, with runnable Python showing real requests and status codes, an idempotency table and REST vs GraphQL vs gRPC.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# REST API explained with a working example

> **Short answer**
>
> **An API** is a set of rules that lets one program ask another for data or actions. A REST API does this over HTTP: URLs name resources, methods such as GET, POST, PUT and DELETE say what to do, and status codes like 200, 201 or 404 report what happened. Responses are usually JSON.

This page is for learners who can call an API from a tutorial but cannot yet say why a create returns 201, why DELETE twice is fine, or when to pick something other than REST. The server and client below run on your own machine with only the Python standard library, and the output shown is what they printed on 1 December 2026 on Python 3.9.6.

It does not repeat how to deploy one. For that, see [deploy a Python API free](https://www.masaischool.com/resources/build/deploy-python-api-free), and for the role that builds these daily, the [backend developer roadmap](https://www.masaischool.com/resources/backend-developer-roadmap).

1. **Client** - sends method, URL and body
2. **HTTP** - carries the request over the network
3. **Server** - runs code, touches the database
4. **Response** - status code, headers and JSON body
One request and response cycle.

## What a REST API is, shown in 11 real requests

An API (application programming interface) is a contract between programs: send this, get that. REST (representational state transfer) is a style for web APIs that treats everything as a resource with a URL, such as /notes/1. The method says the action, the status code says the outcome, and each request carries everything the server needs, so the server keeps no conversation state between calls.

The block below starts a tiny notes server on a random local port using http.server, then calls it with urllib. Run it yourself: nothing to install.import json, threading, urllib.request, urllib.error from http.server import BaseHTTPRequestHandler, HTTPServer NOTES = {} # id -> {"id": ..., "text": ...} NEXT_ID = [1] class Handler(BaseHTTPRequestHandler): def log_message(self, *args): # keep the demo output clean pass def send_json(self, status, body=None, headers=None): data = json.dumps(body).encode() if body is not None else b"" self.send_response(status) if body is not None: self.send_header("Content-Type", "application/json") for k, v in (headers or {}).items(): self.send_header(k, v) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def read_json(self): length = int(self.headers.get("Content-Length", 0)) try: return json.loads(self.rfile.read(length) or b"null") except ValueError: return None def note_id(self): parts = self.path.strip("/").split("/") return parts[1] if len(parts) == 2 and parts[0] == "notes" else None def do_GET(self): nid = self.note_id() if self.path == "/notes": self.send_json(200, list(NOTES.values())) elif nid in NOTES: self.send_json(200, NOTES[nid]) else: self.send_json(404, {"error": "not found"}) def do_POST(self): body = self.read_json() if not isinstance(body, dict) or "text" not in body: return self.send_json(400, {"error": "send JSON with a text field"}) nid = str(NEXT_ID[0]); NEXT_ID[0] += 1 NOTES[nid] = {"id": nid, "text": body["text"]} self.send_json(201, NOTES[nid], {"Location": "/notes/" + nid}) def do_PUT(self): nid, body = self.note_id(), self.read_json() if nid not in NOTES: return self.send_json(404, {"error": "not found"}) if not isinstance(body, dict) or "text" not in body: return self.send_json(400, {"error": "send JSON with a text field"}) NOTES[nid] = {"id": nid, "text": body["text"]} self.send_json(200, NOTES[nid]) def do_DELETE(self): nid = self.note_id() if NOTES.pop(nid, None) is None: return self.send_json(404, {"error": "not found"}) self.send_json(204) server = HTTPServer(("127.0.0.1", 0), Handler) base = "http://127.0.0.1:%d" % server.server_port threading.Thread(target=server.serve_forever, daemon=True).start() def call(method, path, body=None, raw=None): data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None) req = urllib.request.Request(base + path, data=data, method=method, headers={"Content-Type": "application/json"}) try: r = urllib.request.urlopen(req) except urllib.error.HTTPError as e: r = e text = r.read().decode() loc = r.headers.get("Location") print(f"{method:6} {path:9} -> {r.status} {text or '(empty body)'}" + (f" Location: {loc}" if loc else "")) call("POST", "/notes", {"text": "buy milk"}) call("GET", "/notes/1") call("PUT", "/notes/1", {"text": "buy oat milk"}) call("PUT", "/notes/1", {"text": "buy oat milk"}) # same request again: same result call("POST", "/notes", {"text": "call mum"}) call("POST", "/notes", {"text": "call mum"}) # same request again: a new note call("GET", "/notes") call("DELETE", "/notes/1") call("DELETE", "/notes/1") # repeat: state is the same, status differs call("GET", "/notes/1") call("POST", "/notes", raw=b"not json") server.shutdown()

Output, exactly as printed:POST /notes -> 201 {"id": "1", "text": "buy milk"} Location: /notes/1 GET /notes/1 -> 200 {"id": "1", "text": "buy milk"} PUT /notes/1 -> 200 {"id": "1", "text": "buy oat milk"} PUT /notes/1 -> 200 {"id": "1", "text": "buy oat milk"} POST /notes -> 201 {"id": "2", "text": "call mum"} Location: /notes/2 POST /notes -> 201 {"id": "3", "text": "call mum"} Location: /notes/3 GET /notes -> 200 [{"id": "1", "text": "buy oat milk"}, {"id": "2", "text": "call mum"}, {"id": "3", "text": "call mum"}] DELETE /notes/1 -> 204 (empty body) DELETE /notes/1 -> 404 {"error": "not found"} GET /notes/1 -> 404 {"error": "not found"} POST /notes -> 400 {"error": "send JSON with a text field"}

- Line 1: POST created a resource, so the server answered **201** and a Location header pointing at the new URL.
- Lines 3 and 4: the same PUT twice gives the same result. Lines 5 and 6: the same POST twice made two notes (ids 2 and 3).
- Lines 8 and 9: the first DELETE returns **204** with no body. The second returns **404**, yet the end state, note 1 absent, is the same.
- Last line: bad input gets **400**, a client error, not a crash. This is the habit that separates a usable API from a fragile one.

## HTTP methods and idempotency

A method is **safe** if it only reads, and **idempotent** if sending the same request many times has the same effect on the server as sending it once. [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html) states that PUT, DELETE and the safe methods are idempotent, and POST is not. This matters because clients, proxies and mobile apps retry on timeouts: only idempotent calls can be retried without thinking.

| Method | Typical use | Safe | Idempotent | In the demo above |
|---|---|---|---|---|
| GET | Read a resource or a list | Yes | Yes | Returns 200 with the same data each time |
| POST | Create a resource, or run an action | No | No | Two identical calls made notes 2 and 3 |
| PUT | Replace a resource at a known URL | No | Yes | Same body twice gave the same note |
| PATCH | Change part of a resource | No | Not guaranteed | Not in the demo; depends on how you write it |
| DELETE | Remove a resource | No | Yes | Second call differs in status, not in end state |
| HEAD and OPTIONS | Metadata and allowed methods | Yes | Yes | Not in the demo |

Idempotent does not mean the response is identical: the second DELETE returned 404. It means the server ends in the same state. When a POST must be retry-safe, as in payments, clients send an idempotency key and the server stores it; the [microservices page](https://www.masaischool.com/resources/microservices-vs-monolith-explained) has a runnable example of what goes wrong without one.

## Status codes you actually need

Status codes are grouped by first digit: 2xx success, 3xx redirect, 4xx the client got it wrong, 5xx the server failed. The full registry is on [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status). These twelve cover nearly every API.

| Code | Meaning | Return it when |
|---|---|---|
| 200 OK | Success with a body | A read or update worked |
| 201 Created | A new resource exists | POST created something; add a Location header |
| 204 No Content | Success, nothing to send | DELETE worked; an update with no body |
| 400 Bad Request | Malformed request | Invalid JSON, missing field |
| 401 Unauthorized | Not authenticated | No token or an expired one |
| 403 Forbidden | Authenticated but not allowed | A student calling an admin endpoint |
| 404 Not Found | No such resource | Unknown id or URL |
| 409 Conflict | Clashes with current state | Duplicate email, edit based on a stale version |
| 422 Unprocessable Content | Valid syntax, invalid meaning | Age of -5 in a well-formed JSON body |
| 429 Too Many Requests | Rate limit hit | Client exceeded its allowance |
| 500 Internal Server Error | Server bug | An unhandled exception |
| 503 Service Unavailable | Temporarily down | Maintenance or overload |

The classic confusion is 401 versus 403: 401 means we do not know who you are, 403 means we know and you may not. Whether to use 400 or 422 for validation errors is a team convention; pick one and document it.

## REST vs GraphQL vs gRPC

REST is the default for public and web-facing APIs. The other two solve narrower problems. Details differ by tool, so check the official pages ([GraphQL](https://graphql.org/learn/), [gRPC](https://grpc.io/docs/what-is-grpc/introduction/)) before choosing.

| Style | One line | Pick it when |
|---|---|---|
| REST | Many URLs, one per resource, using HTTP methods and status codes | Public APIs, CRUD apps, anything cached by browsers and CDNs |
| GraphQL | One endpoint where the client asks for exactly the fields it needs | Many different clients, deeply nested data, over-fetching hurts |
| gRPC | Binary calls defined in a schema, used mostly between backend services | Internal service-to-service calls where speed and typed contracts matter |

Most freshers should build REST first. It reuses what the browser and HTTP already give you. Frameworks that make it quick are compared in [Django vs Flask vs FastAPI](https://www.masaischool.com/resources/django-vs-flask-vs-fastapi).

## Seven REST API design mistakes

1. **Verbs in URLs.**/getNotes and /deleteNote/5 repeat what the method already says. Use GET /notes and DELETE /notes/5.
2. **Always returning 200.** Putting {"success": false} inside a 200 hides errors from every client, monitor and retry library.
3. **Using POST for everything.** You lose idempotency and caching. Use GET to read and PUT to replace.
4. **Inconsistent error bodies.** Pick one shape, such as {"error": "message"}, and use it everywhere, as the demo does.
5. **No pagination.**GET /notes returning a million rows will take the server down. Add limit and a cursor or page parameter.
6. **Leaking internals.** Database column names and stack traces in responses help attackers and lock you into the schema.
7. **No versioning plan.** Changing a field name breaks clients. Add /v1/ or a header from day one, and never remove fields without notice.

Security is a separate topic: authentication, rate limiting and input validation need their own care. For practising on real endpoints, see [backend project ideas](https://www.masaischool.com/resources/projects/backend-project-ideas), and for the cloud side, [free backend and database for AI apps](https://www.masaischool.com/resources/tools/free-backend-and-database-for-ai-apps).

## Frequently asked questions

### What is the difference between an API and a REST API?

An API is any interface that lets one piece of software use another, including libraries and operating systems. A REST API is a web API that follows REST conventions: resources identified by URLs, standard HTTP methods, status codes and usually JSON. Not every web API is RESTful; SOAP, GraphQL and gRPC are others.

### What is the difference between PUT and POST?

POST usually creates a resource and lets the server choose its URL, so sending it twice creates two. PUT replaces a resource at a URL the client names, so sending it twice leaves the same result. That makes PUT idempotent and POST not, which affects whether it is safe to retry after a timeout.

### What does idempotent mean in a REST API?

A method is idempotent if repeating the same request leaves the server in the same state as sending it once. GET, PUT and DELETE are idempotent. The responses can still differ: a repeated DELETE can return 404 the second time. Idempotency is what makes automatic retries safe.

### When should I return 201 instead of 200?

Return 201 Created when a request has made a new resource, typically after POST, and include a Location header with its URL. Return 200 when the request succeeded and you are returning a result of a read or update. Use 204 when it succeeded and there is nothing to send back.

### Is REST better than GraphQL?

Neither is better in general. REST is simpler, works with browser and CDN caching, and suits most apps. GraphQL helps when many clients need different slices of the same data or when over-fetching is a measured problem. Start with REST and move only if you hit that problem.

### What is the difference between 401 and 403?

401 means the server does not know who you are: the credentials are missing, wrong or expired. 403 means it knows who you are, but your account is not allowed to do this. Returning the right one tells the client whether to log in again or give up.
