Lesson 7 / 32

Serving HTTP with Functions

Put a function behind an HTTP front door, read the request event, and return a well-formed HTTP response.

By · 15 years in web development

The front door turns requests into events

To serve web or mobile clients, a function sits behind an HTTP front door. On AWS that is API Gateway (REST APIs or HTTP APIs) or a simpler function URL; other platforms have equivalents. The front door terminates TLS and can handle routing, authorisation, throttling and CORS, then turns each HTTP request into an event object. With API Gateway HTTP APIs using payload format 2.0 (also used by function URLs), the event has fields such as rawPath, queryStringParameters, headers, a string body and requestContext.http.method. Your handler returns an object with statusCode, optional headers and a string body; forgetting JSON.stringify on the body is a classic bug. Binary request bodies arrive base64-encoded, flagged by isBase64Encoded: true. If you prefer a full web framework, adapter libraries translate these events into Express-style requests, at some cost in package size and cold start time.

A small weather endpoint

The handler reads the method and a query parameter from the event and returns a JSON body as a string. Called locally with a fake payload-2.0 event:

// HTTP API (payload format 2.0) style handler
export const handler = async (event) => {
  const method = event.requestContext.http.method;
  const city = event.queryStringParameters?.city ?? 'Pune';

  if (method !== 'GET') {
    return { statusCode: 405, body: JSON.stringify({ error: 'GET only' }) };
  }
  return {
    statusCode: 200,
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ city, tempC: 31 }),
  };
};

const event = {
  rawPath: '/weather',
  queryStringParameters: { city: 'Chennai' },
  requestContext: { http: { method: 'GET' } },
};
console.log(await handler(event));

Output:

{
  statusCode: 200,
  headers: { 'content-type': 'application/json' },
  body: '{"city":"Chennai","tempC":31}'
}

The gateway has its own timeout

API Gateway's integration timeout (around 30 seconds by default) is much shorter than Lambda's 15-minute maximum, and users will not wait that long anyway. For slow work, accept the request, put a job on a queue, return 202 Accepted with a job ID, and let the client poll or receive a notification.

Quick check: A handler returns `{ statusCode: 200, body: { ok: true } }` behind API Gateway. What is wrong?

  • Nothing; API Gateway serialises objects automatically in every configuration
  • The status code must be a string
  • Handlers behind HTTP must return a Promise of a Response object
  • The body should be a string, for example `JSON.stringify({ ok: true })`
Answer

The body should be a string, for example `JSON.stringify({ ok: true })` — Proxy integrations expect a string body. Serialise objects yourself and set a content-type header.