Working with RESTful APIs
This domain tests HTTP semantics plus the requests, json and xml.etree modules. You must know which methods are idempotent, what each status class means, and - most often - what a short client snippet returns or raises.
HTTP semantics
- GET is safe and idempotent; PUT replaces a whole resource and is idempotent; PATCH is partial and not guaranteed idempotent; DELETE is idempotent; POST is neither safe nor idempotent, so retrying it can create duplicates.
- 2xx success (201 created, 204 no content), 3xx redirect, 4xx client fault - 400 malformed, 401 unauthenticated, 403 forbidden, 404 missing, 405 wrong method, 409 conflict, 422 validation, 429 rate-limited with
Retry-After- and 5xx server fault. - REST constraints: stateless client-server, cacheable, layered, uniform interface; all state travels in the request, none is held on the server.
requests, JSON and XML
requests.get(url, params={'page': 2}, headers={...}, timeout=5);paramsbuilds the query string for you.json=payloadserialises and setsContent-Type: application/json;data=payloadwith a dict form-encodes it;data=json.dumps(payload)sends a bare string with no JSON header.response.status_code,.headers,.text,.json();raise_for_status()raisesHTTPErroron 4xx/5xx, whichrequestsotherwise never does.json.dumps(obj, indent=2)fails ondatetimeandset;json.loadsyields dicts and lists. XML:ET.fromstring(text),root.findall('item'), element.textand.attrib.
Worked example
r = requests.get(f'{BASE}/items', params={'page': 2}, timeout=5)
r.raise_for_status()
items = r.json()['results']
Reasoning: without raise_for_status(), a 404 body would flow into r.json() and surface as JSONDecodeError instead of a clear HTTP error; timeout prevents a hung socket. params encodes ?page=2, so no manual string concatenation is needed.
Traps
- Calling
.json()on a 204 or an HTML error page raises;response.okis false only for status ≥ 400. - Passing both
json=anddata=in one call is an error, and putting a token in the URL instead of aAuthorization: Bearerheader leaks it into logs.