API gateway fundamentals
What is an API gateway?
An API gateway is a managed or self-operated entry point for application programming interfaces (APIs). It receives client requests and selects a backend using a contract such as a method and path. Depending on the product, it can also enforce authentication policies, limit traffic, transform messages and collect telemetry. It does not replace business logic or a database.
Byte Books has a browser storefront and an order service. Instead of teaching the browser the address of every backend, publish one API name, such as https://api.example.com. A request to GET /v1/orders/B17 reaches the gateway, which applies its route policy before forwarding to the order service. The service still checks that the caller may view order B17. No actual domain or endpoint is created.
Follow the request through the system
Browser -> DNS/TLS -> API gateway -> order service -> database route, policy ownership checkA route pairs an HTTP method with a path (and sometimes additional matching conditions). GET reads a resource; PUT generally requests creation or replacement at a known URI. A schema describes accepted data types, required properties and response shapes. An OpenAPI description can document routes and schemas, but importing it does not automatically implement every validation rule: check the gateway feature set and backend validation.
A backend integration connects a route to an HTTP service, function or other supported target. For instance, the gateway can forward the order ID and trusted identity context to a function. Do not copy client-supplied identity headers into trusted fields. Verify gateway-to-backend authentication and prevent direct access that bypasses the intended policies. A transformation can adapt a field name for a legacy backend, but must preserve semantics and avoid leaking internal or sensitive fields.
Three independent checks
Authentication establishes who is calling; authorization establishes which action and resource that identity may access; network controls establish whether a connection can reach an endpoint. A valid login does not entitle a customer to read another customer's order. A private endpoint is not a substitute for application authorization. A project or subscription API key may identify a consuming application for quota tracking, but is not by itself proof of a user's identity.
For token-based identity, validate issuer, audience, signature and lifetime according to the identity system, then enforce resource ownership at the backend. Use short-lived credentials and never record complete authorization headers. In this lesson the identity comes from a trusted offline fixture, not from a real credential.
An offline API contract and mock service
Use this deliberately small contract for an existing order. The only permitted caller is its fictional owner. GET returns the stored example quantity; PUT previews replacement of the only mutable field, quantity, which must be an integer from 1 through 10. The mock returns an HTTP-like status and dictionary, not an actual HTTP response. It does not authenticate tokens, mutate a database, implement HTTP transport or represent a provider SDK.
GET /v1/orders/B17 -> 200 {id, quantity}PUT /v1/orders/B17 {quantity: integer 1..10} -> 200 {id, quantity}Errors -> {error: stable_string}Run the following standalone Python 3 example locally; no dependencies, network or credentials are required.
def respond(method, path, principal, body=None, available=True): # principal is already authenticated by a trusted test fixture. if path != "/v1/orders/B17": return 404, {"error": "not_found"} if method not in ("GET", "PUT"): return 405, {"error": "method_not_allowed"} if principal is None: return 401, {"error": "authentication_required"} if principal != "owner": return 403, {"error": "forbidden"} if method == "PUT": if (not isinstance(body, dict) or set(body) != {"quantity"} or type(body["quantity"]) is not int or not 1 <= body["quantity"] <= 10): return 400, {"error": "invalid_quantity"} if not available: return 503, {"error": "temporarily_unavailable"} if method == "GET": return 200, {"id": "B17", "quantity": 2} # Preview only: no persistent change is performed. return 200, {"id": "B17", "quantity": body["quantity"]}
for request in [("GET", "owner", None), ("PUT", "owner", {"quantity": 3}), ("GET", "guest", None)]: method, principal, body = request status, data = respond(method, "/v1/orders/B17", principal, body) print(status, data)Expected output:
200 {'id': 'B17', 'quantity': 2}200 {'id': 'B17', 'quantity': 3}403 {'error': 'forbidden'}The first call reads the example order; the second previews a valid replacement; the third denies a different authenticated identity. A Boolean quantity is rejected even though Python's bool is a subclass of int. The mock intentionally returns 404 for an unknown path before authentication, a disclosed route-order choice for this public contract. Actual gateways can evaluate policies in a different order. A real 401 response needs a suitable WWW-Authenticate challenge, and a real 405 response must include Allow; the tuple mock omits headers. A real PUT must persist the requested change or report its true outcome, not pretend the preview wrote data.
Browser CORS and custom domains
A browser's origin combines scheme, host and port. https://shop.example.com and https://api.example.com have different origins. CORS is the browser mechanism that controls whether cross-origin script access is permitted. Some requests cause the browser to send an OPTIONS preflight asking about the intended method and headers. Configure the precise storefront origin and permitted methods/headers; credentialed requests cannot use a wildcard allowed origin. Verify preflight handling with the selected gateway and ensure error responses expose the intended CORS headers. CORS does not stop non-browser clients, and it does not provide authorization or replace CSRF protections for cookie-based sessions.
A custom API domain requires DNS and a valid TLS certificate for the name. DNS maps the name to the gateway endpoint; the gateway maps requests to the intended API/stage or deployment. Test the mapping, certificate and backend identity separately. Use the private integration or other access design supported by the selected product.
Compare gateway products
- Amazon API Gateway: REST and HTTP APIs differ in features. For example, the official comparison lists per-client usage throttling for REST APIs, not HTTP APIs. Both have CORS configuration, with different mechanics. Check private endpoint and request validation capabilities for the chosen API type.
- Azure API Management: policies can apply transformations and traffic rules; check tier and scope. A managed gateway, policy engine and developer-facing API management are related but distinct responsibilities.
- Google Cloud API Gateway: an OpenAPI definition configures API behavior and supported security schemes. Check supported OpenAPI versions and backend permissions. Apigee is a broader API management option with policies and developer portal capabilities. Do not assume it is simply another name for API Gateway.
Choose using required authorization, private backend connectivity, schema handling, policy scope, observability and cost. No feature or tier is assumed available in every region. Source anchors: AWS API type comparison, Azure policies, Google OpenAPI overview, Apigee.
Diagnose by layer
A 400 suggests invalid input, 401 missing or unacceptable authentication, 403 refusal despite understanding the request, 404 missing resource or route, and 405 an unsupported method for the resource. A 503 indicates temporary unavailability; 502/504 may indicate upstream response or timeout problems. Exact status mapping varies with gateway policies. Correlate a generated request ID, route, response status, upstream status and latency in gateway and service logs. Redact tokens and customer data; log a small allowlist of fields. First reproduce with a safe test identity, then inspect policy and backend availability; do not disable authentication to fix a denial.
Practice: predict the mock result for a missing principal, quantity 11, and an unavailable backend. Next, learn how to limit traffic and evolve an API contract without breaking clients.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
API gateway fundamentals — knowledge check
Choose the best answer for each offline scenario.
Which information selects the route in the example?
A signed-in guest requests an order owned by another user. What check remains necessary?
What does the mock return for PUT with quantity true?
What does CORS control?
The backend is temporarily unavailable after policy checks. Which status is used by the mock?