JSON endpoints, flask_restful resources and curl.
Open the interactive lessons →REST APIs & Flask-RESTful past questions
Contents
- Start here: JSON and HTTP for programs, from zero
- APIs, SDKs, OpenAPI and documentation
- HTTP methods with curl
- JSON responses in Flask
- Resource classes and method mapping
- URLs and arguments for resources
- reqparse and marshal_with
- Caching and status codes
1. Start here: JSON and HTTP for programs, from zero
An API is a web server that answers programs with JSON instead of answering people with pages.
what an API exchanges and how Python reads it
The question this lesson answers. A program, not a person, reads the reply. What changes when a Python value travels as JSON and comes back?
A web page is made for a person to look at. An API is made for a program to read. When a phone app shows your timetable, it asks a server's API for the data, gets back JSON, and draws the screen itself. Flask can do both jobs: return HTML for people, or return JSON for programs.
Python values and their JSON text
| Python | JSON |
|---|---|
{"ok": True} | {"ok": true} |
None | null |
(1, 2) (a tuple) | [1, 2] (an array) |
{1: "x"} (a number key) | {"1": "x"} (keys are always strings) |
Serialising turns a Python value into JSON text (json.dumps); parsing turns JSON text back into a value (json.loads). Flask serialises for you when a view returns a dict or list, and parses for you when you read request.json.
JSON is like a form that every country can read: it has fixed boxes (objects with quoted keys, arrays, strings, numbers, true, false, null). Python fills the form in its own words (True, None) and the form is copied out in the shared words (true, null). The analogy stops at keys: on the JSON form every key is written as text, even numbers.
Why it works this way. Programs written in different languages need one shared spelling. JSON is that spelling, so Python's own words are translated on the way out and translated back on the way in.
Worked example: Read a JSON reply
Problem.
An API replies with {"name": "Asha", "marks": [80, 92], "passed": true, "note": null}.
Idea.
Arrays become lists; null becomes None.
- data["marks"] is the list [80, 92]; index 1 is 92.
- data["note"] is None.
- data["passed"] is True.
Answer.
92 and None
Common mistake.
Writing null or true in Python code: after parsing they are None and True.
Worked example: Send JSON the right way
Problem.
A Flask route reads request.json. Client A sends {"a": 1} with Content-Type application/json; client B sends the same text without that header.
Idea.
Flask parses the body as JSON only when the Content-Type says it is JSON.
- A: the header is right, request.json is {"a": 1}, status 200.
- B: the body is not marked as JSON; in Flask 3 reading request.json gives 415 Unsupported Media Type.
- request.get_json(silent=True) would give None instead of failing.
Answer.
200 for A, 415 for B
Common mistake.
Assuming the body is read as JSON because it looks like JSON.
A value crossing the network: Python value, then serialise to JSON text, then send over HTTP, then parse into the client's value
How to answer
| Step | Do this |
|---|---|
| 1 | Decide the direction: Python to JSON, or JSON to Python. |
| 2 | Change True, False and None to their other spelling. |
| 3 | Write every key as a string. |
| 4 | Write tuples as arrays. |
Worked example: There and back again
Problem.
s = json.dumps({1: True, 2: None}), then d = json.loads(s). What is s, and does d[1] work?
Idea.
JSON keys are strings.
- The number keys are written as strings.
TruebecomestrueandNonebecomesnull.- So
sis{"1": true, "2": null}. - After loading, the key is the string "1".
Answer.
d[1] raises KeyError; use d["1"].
Common mistake.
Assuming a round trip gives back the same keys.
After parsing JSON, every object key is a string.
Keys come back as text; tuples come back as lists.
2. APIs, SDKs, OpenAPI and documentation
An API is a menu of operations; docs and OpenAPI describe the menu.
what an API is and the words around it
The question this lesson answers. What do the words API, SDK and OpenAPI each stand for, so that a statement about them can be judged true or false?
Terms
| Term | Meaning |
|---|---|
| API | the operations a service exposes (for a web API: URLs, methods, request and response formats) |
| SDK | a software development kit: libraries (often wrapping an API), tools, samples, docs |
| OpenAPI Specification (OAS) | a standard, language-agnostic format (YAML/JSON) to describe REST APIs |
| API documentation / reference | the human-readable list of endpoints, parameters and response formats |
| API key / OAuth token | credentials for calling an API, not descriptions of it |
Using a documented API: read the API description, then send a request to an endpoint, then the server runs the operation, then read the status and the data
An API is a restaurant's menu and ordering rules. An SDK is a starter kit that includes the menu plus tools to order easily. OpenAPI is a standard format for writing menus so any tool can read them. The analogy stops at money: API keys are like membership cards, not part of the menu.
Worked example: SDK or API change?
Problem.
S1: an SDK may include a library that calls the web API for you. S2: installing an SDK changes which requests the server accepts.
Idea.
An SDK is client-side tooling around an API; the server decides what it accepts.
- S1 true: wrapping the calls is the usual job of an SDK.
- S2 false: nothing on the server changes when you install something.
Answer.
S1 true, S2 false
Common mistake.
Treating SDK and API as the same thing.
Worked example: What an OpenAPI file gives
Problem.
A front-end team must start before the server is written. The back-end team hands them an OpenAPI file.
Idea.
OpenAPI is a machine-readable description of a REST API, not running code.
- It lists paths and methods, such as POST
/books. - It lists required parameters, body fields and response shapes.
- It does not run the server, store data or prove the server behaves that way.
Answer.
The agreed interface: endpoints, inputs and responses
Common mistake.
Expecting the file to contain the server's logic.
Why it works this way. An API is the promise a server makes. An SDK is a helper written for one programming language to use that promise. A description file such as OpenAPI writes the promise down so tools can read it.
The verbs and what they promise. REST uses HTTP methods as verbs on a resource. Two properties matter in exam statements: safe (the request does not change anything on the server) and idempotent (sending it twice has the same effect as sending it once).
HTTP methods in REST
| Method | Typical use | Safe | Idempotent |
|---|---|---|---|
| GET | read a resource | yes | yes |
| POST | create a new resource | no | no (two POSTs make two items) |
| PUT | replace or update a resource | no | yes |
| DELETE | remove a resource | no | yes |
Worked example: Which request is not idempotent?
Problem.
A client retries each request after a timeout: GET /items, PUT /items/3, DELETE /items/3, POST /items.
Idea.
Idempotent means repeating has no extra effect.
- GET twice reads twice; nothing changes.
- PUT twice sets item 3 to the same value.
- DELETE twice: the item is gone after the first.
- POST twice creates two items.
Answer.
POST /items
Common mistake.
Picking DELETE because the second one fails: a failed second call still leaves the same state.
Resources are nouns, methods are verbs. A REST URL names a thing (/students/7), never an action (/getStudent?id=7). The HTTP method says what to do with it. This is why the same URL can answer GET, PUT and DELETE differently.
Designing URLs
| Not REST-style | REST-style | Method |
|---|---|---|
| /getAllStudents | /students | GET |
| /addStudent | /students | POST |
| /updateStudent?id=7 | /students/7 | PUT |
| /deleteStudent?id=7 | /students/7 | DELETE |
Worked example: Documentation is not the API
Problem.
A team deletes its OpenAPI file but changes no code. Does the API stop working?
Idea.
The file describes the service; it does not run it.
- The endpoints are still served by the code.
- Only the description is gone.
Answer.
No.
Common mistake.
Treating the description as the implementation.
- An SDK is the bigger box: it can contain API libraries plus tools.
- OAS describes an API; it is not the code that runs it.
- Judge each option of a theory question separately.
API is the contract, SDK the helper, OpenAPI the written description.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Underline the subject of the statement. |
| 2 | Ask whether it is the contract, the helper or the description. |
| 3 | Test the claim against that meaning. |
3. HTTP methods with curl
-X picks the verb, -d sends data, -H adds headers.
how curl chooses the method and sends data
The question this lesson answers. From the command alone, what does the server receive: which method, and where is the data?
A curl command is the whole HTTP request spelled out: the verb, the labels on the envelope, the contents and the address.
curl flags
| Flag | Meaning |
|---|---|
| (none) | GET |
-X PUT | use method PUT (also POST, DELETE, …) |
-d "a=1&b=2" | send form data (application/x-www-form-urlencoded); implies POST if no -X |
-H "Content-Type: application/json" | declare the body as JSON |
--json '{...}' | JSON body with JSON headers; POST unless -X overrides |
-L | follow redirects |
curl -X PUT -d "status=active&role=admin" http://127.0.0.1:5000/u
Why it works this way. curl chooses the method from what you give it. Sending a body only makes sense for a request that carries data, so -d switches the default from GET to POST.
Worked example: Reading a curl command
Problem.
What does curl -X PUT -d "status=active&role=admin" URL do?
Idea.
-X sets the method; -d sends form-encoded data.
-X PUT: a PUT request.-d "k=v&...": form-encoded data, not JSON.
Answer.
a PUT request sending form data
Common mistake.
Calling it JSON because it carries data.
Worked example: Lower-case methods
Problem.
curl URL -X get against a resource with get and put. Does it work?
Idea.
Flask upper-cases the request method.
- curl sends the method
get. - Werkzeug upper-cases it to
GET, which the resource supports.
Answer.
it works (200)
Common mistake.
Expecting 405 because of the lower case.
Reading a curl command flag by flag. Read it in this order: the method (-X, or POST if there is -d and no -X, otherwise GET), then the headers (-H), then the body (-d or --json), then the URL. Whatever the server returns is printed; add -i to see the status line and headers as well.
curl flags you meet
| Flag | Meaning | Example |
|---|---|---|
-X METHOD | set the method | -X DELETE |
-d DATA | send a body (form-encoded); implies POST | -d "a=1&b=2" |
-H "K: V" | add a header | -H "Content-Type: application/json" |
--json DATA | send JSON with the JSON headers; implies POST | --json '{"a":1}' |
-i | print the status line and headers too | curl -i URL |
Worked example: What method, what body?
Problem.
curl -H "Content-Type: application/json" -d '{"n": 3}' http://127.0.0.1:5000/items
Idea.
-d without -X means POST; the header says the body is JSON.
- No -X but there is -d: POST.
- Content-Type is application/json, so request.json (or reqparse) reads {"n": 3}.
Answer.
POST, body read as JSON
Common mistake.
Answering GET because no -X is given.
Reading a curl command: method: -X, else POST with -d, else GET, then headers: -H, then body: -d or --json, then address
Worked example: A wrong label
Problem.
curl -H "Content-Type: application/json" -d "n=3" URL, and the view reads request.json. What happens?
Idea.
The header says JSON but the body is not JSON.
-dsends a POST with the bodyn=3.- The header declares the body as JSON.
- Flask tries to parse
n=3as JSON and fails.
Answer.
A 400 Bad Request.
Common mistake.
Expecting request.json to be {"n": 3}.
The header must describe what the body really is.
-X names the method; -d means form data; --json means JSON.
4. JSON responses in Flask
Return a dict or jsonify(...) and Flask sends JSON with status 200.
jsonify and dict returns
The question this lesson answers. A view returns Python data. Exactly which status, type and text does the client receive?
The view hands Flask a Python value. Flask packs it as JSON text, labels it application/json and attaches a status code.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/courses")
def courses():
return jsonify([{"id": "CS1001", "name": "CT"}])
@app.route("/")
def home():
return {"a": 1}
Ways to return JSON
jsonify(x) | return {...} | |
|---|---|---|
| Body | JSON of x | JSON of the dict |
| Status | 200 | 200 |
| Mimetype | application/json | application/json |
| Lists | yes | yes (Flask 2.2+) |
Why it works this way. The network carries text. Flask writes your value out as JSON and labels it, so the receiving program knows how to read it.
Worked example: Status and mimetype
Problem.
return jsonify(error="sold out"), 409
Idea.
jsonify sets the JSON mimetype; the second item of the tuple sets the status.
- The body is
{"error": "sold out"}with mimetype application/json. - The tuple replaces the default 200 with 409.
Answer.
409, application/json
Common mistake.
Answering 200 because jsonify was used.
Worked example: A dict holding a list
Problem.
jsonify({"items": [ {"a": 1}, {"b": 2} ]}). What is the shape?
Idea.
The structure is kept: a list stays a list.
- The outer value is an object with one key.
- Its value is an array of two objects, printed with
[ ].
Answer.
{"items": [{"a": 1}, {"b": 2}]}
Common mistake.
Merging the objects into one.
Key order in Flask's JSON. Flask sorts the keys of a JSON object alphabetically by default, both for jsonify and for a returned dict. jsonify({"b": 1, "a": 2}) is sent as {"a":2,"b":1}. The data is the same, but if an option shows the keys in a different order, this is why.
What Flask sends
| View returns | Body sent |
|---|---|
jsonify({"b": 1, "a": 2}) | {"a":2,"b":1} |
{"b": 1, "a": 2} | {"a":2,"b":1} |
Worked example: Same data, different order
Problem.
A view returns {"name": "Asha", "age": 20}.
Idea.
Keys are sorted: age comes before name.
- Sort the keys: age, name.
- Body: {"age":20,"name":"Asha"}.
Answer.
{"age":20,"name":"Asha"}
Common mistake.
Expecting the keys in the order they were written.
How to answer
| Step | Do this |
|---|---|
| 1 | Take the returned value. |
| 2 | Convert it to JSON spelling. |
| 3 | Use status 200 unless the view returns another. |
| 4 | Label it application/json. |
Worked example: A value and a status
Problem.
A view returns {"item": None}, 201. Give the status and the body.
Idea.
The second item of the tuple is the status.
- The first item is the body.
Noneis written asnull.- The second item sets the status to 201.
Answer.
201 with {"item": null}.
Common mistake.
Sending status 200, or writing None in the body.
A returned tuple reads as body first, then status.
Value to JSON text, label application/json, status 200 unless stated.
5. Resource classes and method mapping
GET runs get(), PUT runs put(); a missing method means 405.
how Flask-RESTful maps HTTP verbs to class methods
The question this lesson answers. One class serves one address. How does Flask-RESTful decide which method of the class runs?
One counter with labelled windows: the GET window hands out, the POST window accepts new items, and a missing window turns you away.
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class Greet(Resource):
def get(self):
return {"greet": "Hello from GET"}
def put(self):
return {"greet": "Hello from PUT"}
api.add_resource(Greet, "/a", "/b")
Why it works this way. The HTTP verb already says what the client wants to do, so the class needs no if on the method: each verb has a function of the same name.
Worked example: A missing verb
Problem.
With Greet above, which of GET /a, PUT /b, POST /a fail?
Idea.
POST has no method in the class.
- GET and PUT exist on every registered URL.
- POST does not exist: 405.
Answer.
only POST /a
Common mistake.
Thinking /b only accepts PUT because of its name.
Worked example: Same URL, different verb
Problem.
PUT /delete/val1 for the class in the your-move step, with a put(self, val) method added that returns {"updated": val}.
Idea.
The URL's name means nothing; the verb picks the method.
- The URL matches
/delete/<val>with val = val1. - PUT runs
put(self, val). - Response:
{"updated": "val1"}.
Answer.
{"updated": "val1"}
Common mistake.
Expecting delete() because the URL says delete.
Status codes from a Resource. A resource method returns either the data (sent with 200) or a tuple: (data, status) or (data, status, headers). A method the class lacks gives 405. A class with a get also answers HEAD and OPTIONS; a class without get gives 405 for HEAD.
One class with post and put (no get, no delete)
| Request | Status | Why |
|---|---|---|
POST /r (returns {"id": 7}, 201) | 201 | status from the tuple |
| PUT /r (returns data, 200, headers) | 200 | headers such as Cache-Control are added |
| HEAD /r | 405 | HEAD needs a get method |
| DELETE /r | 405 | no delete method |
Worked example: HEAD and OPTIONS
Problem.
class R(Resource): def get(self): return {"a": 1} registered at /r.
Idea.
get also covers HEAD; OPTIONS is answered automatically.
- HEAD runs like GET without a body: 200.
- OPTIONS lists the allowed methods: 200.
Answer.
200 and 200
Common mistake.
Answering 405 for HEAD because the class has no head method.
One resource, a whole life cycle. The clearest way to see REST is to follow one item through every verb. The class below stores items in a dictionary and returns a status that says what happened each time.
ITEMS = {}
class Item(Resource):
def get(self, i):
return ITEMS.get(i, {"error": "not found"}), (200 if i in ITEMS else 404)
def put(self, i):
ITEMS[i] = {"id": i}
return ITEMS[i], 201
def delete(self, i):
ITEMS.pop(i, None)
return "", 204
api.add_resource(Item, "/items/<int:i>")
The five statuses above, 404, 201, 200, 204 and 404, tell the whole story without reading any body: missing, created, found, deleted, missing again.
Worked example: A plain string
Problem.
A resource's get returns the string "hi". What is the body?
Idea.
Flask-RESTful serialises the return value as JSON.
- The value is a string.
- JSON writes strings in double quotes.
Answer.
"hi" with the quotes.
Common mistake.
Expecting the bare word, as from a plain Flask view.
- Match the HTTP method to the method name in the class before reading the body.
- Check that the URL placeholders and the method parameters have the same names.
- A missing method gives 405, a missing URL gives 404.
The verb picks the method of the same name; no method means 405.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Find the resource for the address. |
| 2 | Look for a method named after the verb. |
| 3 | Run it, or answer 405. |
6. URLs and arguments for resources
Normal URL rules apply; then the method must accept the URL's values.
registering several URLs and matching them
The question this lesson answers. Which addresses reach a resource that expects values inside the path?
Each placeholder is a keyhole of a certain shape. An address opens the route only when every piece fits its shape.
class Power(Resource):
def get(self, x, y):
return {"output": x ** y}
api.add_resource(Power, "/<int:x>/<int:y>")
How to answer
| Step | Do this |
|---|---|
| 1 | Split the rule and the address at each slash. |
| 2 | Match fixed words exactly. |
| 3 | Check each value against its converter. |
| 4 | Pass the matched values to the method by name. |
Why it works this way. The rule is a pattern for the path only. Names such as x and y live in your code; they are never written in the address.
Worked example: Query string versus placeholders
Problem.
For /<int:x>/<int:y>, which works: /6/2, /x=6/y=2, /?x=6&y=2?
Idea.
Placeholders come from path segments that pass the converter.
/6/2: both ints: works./x=6/y=2:x=6is not an int: 404./?x=6&y=2: path/has no rule here: 404.
Answer.
/6/2
Common mistake.
Writing name=value in the path.
Worked example: Odd-looking segments
Problem.
Rule /files/<string:name>/<string:ext>. Does /files/v1.2/tar.gz match?
Idea.
A string placeholder takes any text that has no /.
- First segment:
v1.2; second:tar.gz. - Dots are ordinary characters, so the rule matches.
Answer.
Yes: name = v1.2, ext = tar.gz
Common mistake.
Answering Not Found because of the dots.
Worked example: A negative number
Problem.
A resource is added at /n/<int:i>. What status does GET /n/-1 give?
Idea.
The default int converter accepts only digits.
- The piece
-1starts with a minus sign. - The
intconverter does not accept it. - No rule matches the address.
Answer.
404 Not Found.
Common mistake.
Expecting the method to receive $-1$.
A failed converter gives 404, because the address matches no rule.
One class, several URLs, default arguments. api.add_resource(R, "/r", "/r/<int:i>", endpoint="item") serves both URLs with the same class. If the method has a default (def get(self, i=0)), the URL without the placeholder works too and uses the default.
class R(Resource):
def get(self, i=0):
return {"i": i}
api.add_resource(R, "/r", "/r/<int:i>", endpoint="item")
# GET /r -> {"i": 0}
# GET /r/4 -> {"i": 4}
Worked example: Without the default
Problem.
Same registration, but the method is def get(self, i).
Idea.
/r supplies no i, and the method requires one.
- The URL matches /r.
- get is called with no i: TypeError.
- An unhandled error is a 500.
Answer.
500
Common mistake.
Expecting 404: the URL does match, so it is the method call that fails.
Values go in the slots, never with their names.
7. reqparse and marshal_with
reqparse reads and checks input; marshal_with filters and converts output.
reading request arguments and shaping responses in Flask-RESTful
The question this lesson answers. Who checks the input and shapes the output? The parser guards the way in; marshal_with shapes the way out.
The parser checks each argument against your list before your method uses it: is it present, can it be converted, is it an allowed choice?
parser = reqparse.RequestParser()
parser.add_argument("n", type=int, required=True)
class R(Resource):
def post(self):
return parser.parse_args()
marshal_with
out_fields = {"roll": fields.Integer, "city": fields.String}
class MyApi(Resource):
@marshal_with(out_fields)
def post(self):
return parser.parse_args() # roll, city, phone
What the parser does: find the argument, then convert its type, then check required and choices, then method runs, or 400
Why it works this way. Declaring the arguments once keeps every method free of repeated checks, and gives clients the same error shape each time.
reqparse options that change the result. location="args" reads the query string; default= fills a missing argument; choices= limits the allowed values; type=int converts. A value that breaks a rule gives 400, with a JSON message naming the argument. On the way out, marshal_with converts each field and turns a missing key into null.
reqparse: n (int, default 5) and c (choices red, blue) from the query string
| Request | Status | Parsed |
|---|---|---|
| /r | 200 | {"n": 5, "c": null} |
| /r?n=3&c=red | 200 | {"n": 3, "c": "red"} |
| /r?c=green | 400 | the message names c |
| /r?n=x | 400 | x is not an int |
marshal_with: what each field does
| Field | Returned | Sent |
|---|---|---|
id: fields.String | 7 | "7" |
price: fields.Float | 3 | 3.0 |
tags: fields.List(fields.Integer) | ["1", 2] | [1, 2] |
missing: fields.String | (no key) | null |
| (not listed) extra | 1 | dropped |
Worked example: A required int
Problem.
add_argument("n", type=int, required=True). What do POST {"n": 3} and POST {} give?
Idea.
type converts; required enforces.
{"n": 3}→{"n": 3}.{}→ 400 Bad Request (missing required argument).
Answer.
{"n": 3}, then 400
Common mistake.
Expecting {"n": null}.
Worked example: Filtering output
Problem.
With out_fields above, what does POST {"roll": "12", "city": 45, "phone": "999"} return?
Idea.
marshal_with keeps only the listed keys and converts each to its field type.
- All three declared arguments are parsed.
rollis listed as Integer: 12.cityis listed as String: "45".phoneis not listed, so it is dropped.
Answer.
{"roll": 12, "city": "45"}
Common mistake.
Keeping phone, or leaving the types as they were sent.
Worked example: A choice that is not allowed
Problem.
parser.add_argument("c", choices=("red", "blue"), location="args"). Request /r?c=green.
Idea.
A value outside choices is a client error.
- green is not in (red, blue).
- parse_args stops with 400 and a message about c.
Answer.
400
Common mistake.
Expecting c to be None: that happens only when c is missing, not when it is wrong.
Worked example: A decimal for an integer
Problem.
add_argument("n", type=int, location="args") and the request is ?n=3.5. Status?
Idea.
int cannot convert that text.
- The value arrives as the string "3.5".
int("3.5")raises an error.- The parser reports the failure and stops the method.
Answer.
400 Bad Request.
Common mistake.
Expecting the value to be cut to 3.
Input problems are reported as 400 before the method does its work.
reqparse filters the way in; marshal_with filters the way out.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | List the declared arguments with their rules. |
| 2 | Check the request against each rule. |
| 3 | Shape the result with the declared fields only. |
8. Caching and status codes
Caching keeps copies of responses so the server is asked less.
what caching does and which responses are cached
The question this lesson answers. When may a stored copy be reused, and which status code tells the client what happened?
Instead of walking to the library again, you reuse your copy while it is still fresh. max-age says how long it stays fresh.
A cache stores a response (in the browser, a proxy or a CDN) and reuses it for later identical requests, so they do not reach the server. Caching reduces latency and reduces server load. By default GET (and HEAD) responses are cacheable; POST responses are not cached by default.
Status codes in APIs
| Code | Meaning | Typical use |
|---|---|---|
| 200 | OK | GET, PUT success |
| 201 | Created | POST created a resource |
| 204 | No Content | success with empty body |
| 400 | Bad Request | missing or invalid input |
| 401 | Unauthorized | credentials missing or wrong |
| 404 | Not Found | no such URL or record |
| 405 | Method Not Allowed | verb not supported |
| 415 | Unsupported Media Type | body is not JSON where JSON is expected |
Worked example: True or false
Problem.
Caching increases latency and server load. True?
Idea.
Caching avoids trips to the server.
- Fewer requests reach the server: less load.
- Answers come from a nearer copy: lower latency.
Answer.
false
Common mistake.
Thinking caching adds an extra step.
Worked example: Which requests are cacheable by default?
Problem.
Are all GET and POST requests cacheable by default in browsers?
Idea.
POST responses are not cached by default.
- GET responses can be cached by default.
- POST responses are cached only with explicit freshness headers, which is rare.
Answer.
false
Common mistake.
Treating every method alike.
Why it works this way. Reading does not change anything, so a saved answer to a GET can be correct for a while. A request that changes data must reach the server.
Errors as JSON. In an API, errors should be JSON too. flask_restful.abort(404, message="no item 9") stops the method and sends {"message": "no item 9"} with status 404 and content type application/json, unlike Flask's HTML error page.
from flask_restful import abort
class R(Resource):
def get(self, i):
if i > 3:
abort(404, message="no item {}".format(i))
return {"i": i}
Status codes an API uses
| Code | Meaning | When |
|---|---|---|
| 200 | OK | read or update worked |
| 201 | Created | POST made a new item |
| 204 | No Content | worked, nothing to send back |
| 400 | Bad Request | input missing or wrong |
| 404 | Not Found | no such item or URL |
| 405 | Method Not Allowed | URL exists, verb does not |
| 500 | Server Error | the code crashed |
How a cache decides. A response can carry Cache-Control: max-age=60, which tells browsers and proxies they may reuse it for 60 seconds without asking the server. GET responses are the usual candidates; POST changes data, so it is not cached by default. A resource method can add the header as the third item of its return tuple.
Cache-Control values
| Header | Meaning |
|---|---|
max-age=60 | reuse for 60 seconds |
no-cache | check with the server before reusing |
no-store | never keep a copy (for private data) |
Answering a GET with a cache. stored copy younger than max-age? yes: reuse the copy: no server call. no: ask the server, then store the new copy
How to answer
| Step | Do this |
|---|---|
| 1 | Check the method: GET is the usual candidate. |
| 2 | Read the Cache-Control value. |
| 3 | Compare the age of the stored copy with max-age. |
| 4 | Decide whether the server is contacted. |
Worked example: Fresh or stale
Problem.
A GET reply has Cache-Control: max-age=60. The same GET happens 30 s later and again 90 s after the first. Which reach the server?
Idea.
A copy is fresh for 60 seconds.
- At 30 s the copy is fresh, so it is reused.
- At 90 s the copy is older than 60 s.
- The browser must ask the server again.
Answer.
Only the request at 90 s.
Common mistake.
Thinking every request reaches the server.
no-store means keep nothing; no-cache means keep it but check first.
Cache reads, send writes; the status says what happened.