REST APIs & Flask-RESTful

JSON endpoints, flask_restful resources and curl.

8 lessons · 23 past questions · 78.5 marks in the papers collected here

Open the interactive lessons →REST APIs & Flask-RESTful past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Start here: JSON and HTTP for programs, from zero
  2. APIs, SDKs, OpenAPI and documentation
  3. HTTP methods with curl
  4. JSON responses in Flask
  5. Resource classes and method mapping
  6. URLs and arguments for resources
  7. reqparse and marshal_with
  8. 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

PythonJSON
{"ok": True}{"ok": true}
Nonenull
(1, 2) (a tuple)[1, 2] (an array)
{1: "x"} (a number key){"1": "x"} (keys are always strings)
Definition

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.

Picture it

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.

  1. data["marks"] is the list [80, 92]; index 1 is 92.
  2. data["note"] is None.
  3. 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.

  1. A: the header is right, request.json is {"a": 1}, status 200.
  2. B: the body is not marked as JSON; in Flask 3 reading request.json gives 415 Unsupported Media Type.
  3. 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

StepDo this
1Decide the direction: Python to JSON, or JSON to Python.
2Change True, False and None to their other spelling.
3Write every key as a string.
4Write 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.

  1. The number keys are written as strings.
  2. True becomes true and None becomes null.
  3. So s is {"1": true, "2": null}.
  4. 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.

Check your answer in ten seconds

After parsing JSON, every object key is a string.

Memory line

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

TermMeaning
APIthe operations a service exposes (for a web API: URLs, methods, request and response formats)
SDKa 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 / referencethe human-readable list of endpoints, parameters and response formats
API key / OAuth tokencredentials 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

Picture it

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.

  1. S1 true: wrapping the calls is the usual job of an SDK.
  2. 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.

  1. It lists paths and methods, such as POST /books.
  2. It lists required parameters, body fields and response shapes.
  3. 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

MethodTypical useSafeIdempotent
GETread a resourceyesyes
POSTcreate a new resourcenono (two POSTs make two items)
PUTreplace or update a resourcenoyes
DELETEremove a resourcenoyes

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.

  1. GET twice reads twice; nothing changes.
  2. PUT twice sets item 3 to the same value.
  3. DELETE twice: the item is gone after the first.
  4. 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-styleREST-styleMethod
/getAllStudents/studentsGET
/addStudent/studentsPOST
/updateStudent?id=7/students/7PUT
/deleteStudent?id=7/students/7DELETE

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.

  1. The endpoints are still served by the code.
  2. Only the description is gone.

Answer.

No.

Common mistake.

Treating the description as the implementation.

Tips and tricks
  • 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.
Memory line

API is the contract, SDK the helper, OpenAPI the written description.

Method for any exam question

StepDo this
1Underline the subject of the statement.
2Ask whether it is the contract, the helper or the description.
3Test 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 request written by hand

A curl command is the whole HTTP request spelled out: the verb, the labels on the envelope, the contents and the address.

curl flags

FlagMeaning
(none)GET
-X PUTuse 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
-Lfollow 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.

  1. -X PUT: a PUT request.
  2. -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.

  1. curl sends the method get.
  2. 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

FlagMeaningExample
-X METHODset the method-X DELETE
-d DATAsend a body (form-encoded); implies POST-d "a=1&b=2"
-H "K: V"add a header-H "Content-Type: application/json"
--json DATAsend JSON with the JSON headers; implies POST--json '{"a":1}'
-iprint the status line and headers toocurl -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.

  1. No -X but there is -d: POST.
  2. 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.

  1. -d sends a POST with the body n=3.
  2. The header declares the body as JSON.
  3. Flask tries to parse n=3 as JSON and fails.

Answer.

A 400 Bad Request.

Common mistake.

Expecting request.json to be {"n": 3}.

Check your answer in ten seconds

The header must describe what the body really is.

Memory line

-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?

Packing for the journey

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 {...}
BodyJSON of xJSON of the dict
Status200200
Mimetypeapplication/jsonapplication/json
Listsyesyes (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.

  1. The body is {"error": "sold out"} with mimetype application/json.
  2. 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.

  1. The outer value is an object with one key.
  2. 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 returnsBody 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.

  1. Sort the keys: age, name.
  2. Body: {"age":20,"name":"Asha"}.

Answer.

{"age":20,"name":"Asha"}

Common mistake.

Expecting the keys in the order they were written.

How to answer

StepDo this
1Take the returned value.
2Convert it to JSON spelling.
3Use status 200 unless the view returns another.
4Label 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.

  1. The first item is the body.
  2. None is written as null.
  3. The second item sets the status to 201.

Answer.

201 with {"item": null}.

Common mistake.

Sending status 200, or writing None in the body.

Check your answer in ten seconds

A returned tuple reads as body first, then status.

Memory line

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?

Picture it

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.

  1. GET and PUT exist on every registered URL.
  2. 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.

  1. The URL matches /delete/<val> with val = val1.
  2. PUT runs put(self, val).
  3. 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)

RequestStatusWhy
POST /r (returns {"id": 7}, 201)201status from the tuple
PUT /r (returns data, 200, headers)200headers such as Cache-Control are added
HEAD /r405HEAD needs a get method
DELETE /r405no 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.

  1. HEAD runs like GET without a body: 200.
  2. 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>")
Notice

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.

  1. The value is a string.
  2. JSON writes strings in double quotes.

Answer.

"hi" with the quotes.

Common mistake.

Expecting the bare word, as from a plain Flask view.

Tips and tricks
  • 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.
Memory line

The verb picks the method of the same name; no method means 405.

Method for any exam question

StepDo this
1Find the resource for the address.
2Look for a method named after the verb.
3Run 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?

A lock with a shaped keyhole

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

StepDo this
1Split the rule and the address at each slash.
2Match fixed words exactly.
3Check each value against its converter.
4Pass 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.

  1. /6/2: both ints: works.
  2. /x=6/y=2: x=6 is not an int: 404.
  3. /?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 /.

  1. First segment: v1.2; second: tar.gz.
  2. 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.

  1. The piece -1 starts with a minus sign.
  2. The int converter does not accept it.
  3. No rule matches the address.

Answer.

404 Not Found.

Common mistake.

Expecting the method to receive $-1$.

Check your answer in ten seconds

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.

  1. The URL matches /r.
  2. get is called with no i: TypeError.
  3. An unhandled error is a 500.

Answer.

500

Common mistake.

Expecting 404: the URL does match, so it is the method call that fails.

Memory line

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.

A checklist at the door

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

RequestStatusParsed
/r200{"n": 5, "c": null}
/r?n=3&c=red200{"n": 3, "c": "red"}
/r?c=green400the message names c
/r?n=x400x is not an int

marshal_with: what each field does

FieldReturnedSent
id: fields.String7"7"
price: fields.Float33.0
tags: fields.List(fields.Integer)["1", 2][1, 2]
missing: fields.String(no key)null
(not listed) extra1dropped

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.

  1. {"n": 3} → {"n": 3}.
  2. {} → 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.

  1. All three declared arguments are parsed.
  2. roll is listed as Integer: 12.
  3. city is listed as String: "45".
  4. phone is 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.

  1. green is not in (red, blue).
  2. 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.

  1. The value arrives as the string "3.5".
  2. int("3.5") raises an error.
  3. The parser reports the failure and stops the method.

Answer.

400 Bad Request.

Common mistake.

Expecting the value to be cut to 3.

Check your answer in ten seconds

Input problems are reported as 400 before the method does its work.

Memory line

reqparse filters the way in; marshal_with filters the way out.

Method for any exam question

StepDo this
1List the declared arguments with their rules.
2Check the request against each rule.
3Shape 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?

A photocopy on your desk

Instead of walking to the library again, you reuse your copy while it is still fresh. max-age says how long it stays fresh.

Caching

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

CodeMeaningTypical use
200OKGET, PUT success
201CreatedPOST created a resource
204No Contentsuccess with empty body
400Bad Requestmissing or invalid input
401Unauthorizedcredentials missing or wrong
404Not Foundno such URL or record
405Method Not Allowedverb not supported
415Unsupported Media Typebody 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.

  1. Fewer requests reach the server: less load.
  2. 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.

  1. GET responses can be cached by default.
  2. 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

CodeMeaningWhen
200OKread or update worked
201CreatedPOST made a new item
204No Contentworked, nothing to send back
400Bad Requestinput missing or wrong
404Not Foundno such item or URL
405Method Not AllowedURL exists, verb does not
500Server Errorthe 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

HeaderMeaning
max-age=60reuse for 60 seconds
no-cachecheck with the server before reusing
no-storenever 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

StepDo this
1Check the method: GET is the usual candidate.
2Read the Cache-Control value.
3Compare the age of the stored copy with max-age.
4Decide 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.

  1. At 30 s the copy is fresh, so it is reused.
  2. At 90 s the copy is older than 60 s.
  3. The browser must ask the server again.

Answer.

Only the request at 90 s.

Common mistake.

Thinking every request reaches the server.

Check your answer in ten seconds

no-store means keep nothing; no-cache means keep it but check first.

Memory line

Cache reads, send writes; the status says what happened.

Practise this topic →

Weeks covering this topic

Other MAD 1 topics