PCPP1 study materials
PCPP1 study resources

PCPP1: Working with RESTful APIs

PCPP1 · Work through your exam, one topic at a time.

All guide sections

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); params builds the query string for you.
  • json=payload serialises and sets Content-Type: application/json; data=payload with 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() raises HTTPError on 4xx/5xx, which requests otherwise never does.
  • json.dumps(obj, indent=2) fails on datetime and set; json.loads yields dicts and lists. XML: ET.fromstring(text), root.findall('item'), element .text and .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.ok is false only for status ≥ 400.
  • Passing both json= and data= in one call is an error, and putting a token in the URL instead of a Authorization: Bearer header leaks it into logs.