Python helpers

http_response

Set the status code and headers a custom HTTP endpoint responds with.

http_response(body=None, status: int = 200, headers: dict = None) -> dict

Builds the response of a custom HTTP endpoint. Return it from handle(context) when you need a status other than 200 or extra response headers, such as a 422 for a form with a missing field. Returning any other value sends that value as a 200 JSON response.


Parameters

NameTypeDescription
bodyanyA JSON-serializable response body, or None for no body
statusintHTTP status code, from 200 through 599. 204, 205 and 304 responses have no body
headersdict or NoneExtra response headers: Retry-After, Content-Language, or X-* headers. Limited to 8 KiB in total

X-Request-Id, X-Accel-* and X-Sendfile are managed by Octocom and can't be set. Octocom also sets Cache-Control: no-store on every response.

Returns

A response envelope that only has meaning as the return value of handle(context). An ordinary dict with status and body keys is sent as plain JSON; only this helper creates an HTTP response.

Responses are always JSON. Cookies, redirects, HTML, streaming and binary responses are not supported.


Examples

Reject an unauthenticated caller

import hmac

def handle(context):
    supplied = context["request"]["headers"].get("authorization")
    expected = "Bearer " + get_secret("WAREHOUSE_ENDPOINT_TOKEN")
    if not isinstance(supplied, str) or not hmac.compare_digest(supplied, expected):
        return http_response({"error": "Unauthorized"}, status=401)
    return {"accepted": True}

Validate input

def handle(context):
    body = context["request"]["body"]
    if not isinstance(body, dict) or not body.get("orderId"):
        return http_response({"error": "orderId is required"}, status=422)
    return {"received": body["orderId"]}

Ask the caller to retry later

def handle(context):
    return http_response(
        {"error": "Please try again later"},
        status=429,
        headers={"Retry-After": "30"},
    )

See Custom HTTP endpoints for the request context, authentication, limits and testing.

On this page