HTTP and API design

5 concepts · 10 practice questions

Methods and status codes

Methods carry promises. GET is safe (no side effects) and idempotent. PUT and DELETE are idempotent: sending the same request twice leaves the same state as sending it once. POST is neither, and PATCH is not guaranteed to be. Status codes tell the client what to do next: 4xx means fix the request (400 malformed, 401 not authenticated, 403 authenticated but not allowed, 404 not found, 409 conflicts with current state, 429 slow down), 5xx means the server failed and a retry may help.

@app.put("/users/<user_id>/email")
def set_email(user_id):
    if current_user is None:
        return error(401)              # we do not know who you are
    if current_user.id != user_id:
        return error(403)              # we know you, and you may not
    body = request.get_json()
    if "email" not in body:
        return error(400)              # the request itself is wrong
    if email_taken(body["email"]):
        return error(409)              # clashes with the current state
    save_email(user_id, body["email"])
    return "", 204

Also covered

Idempotency keys
Pagination
Versioning and evolution
gRPC vs REST

Sign in to read the rest and take the 10-question test.

Sign in to continue