• Documentation
  • Pricing
© 2026 Serverless, Inc. All rights reserved.

Framework

  • Overview
  • Documentation
  • Plugins360
  • Pricing

Learn

  • Blog
  • GuidesUpdated
  • Examples240
  • Courses

Resources

  • Support
  • Security
  • Trust Center
  • Status

Community

  • Slack
  • GitHub47k
  • Forum
  • Meetups

Company

  • About
  • Careers
  • Contact
  • Partners

Legal

  • Terms of Service
  • Privacy Policy
  • Trademark
  • DMCA
Serverless Framework Logo

Serverless Framework

Intro
SetupUpgrading To V4ConceptsTutorialAWS CredentialsLicense Keys
DeployingPackagingBuildingTestingDev ModeServicesFunctions
OverviewHTTP (API Gateway v2)REST (API Gateway v1)ActiveMQApplication Load BalancerAlexa SkillAlexa Smart HomeCloudWatch EventCloudWatch LogCloudFrontCognito User PoolEventBridge EventIoTIoT Fleet ProvisioningKafkaKinesis & DynamoDBMSKRabbitMQS3ScheduleSNSSQSWebsocket
LayersManaged InstancesWeb Apps (Lambda Web Functions)Sandboxes (Lambda MicroVMs)MCP ServersAlertsVersion PruningDomainsIAM Function PermissionsParameters
OverviewSelf-reference serverless.ymlServerless CoreEnvironment VariablesCLI OptionsExternal YAML/JSON FilesJavascript propertiesGitDoppler
OverviewS3 ObjectsSSM Parameter Store & Secrets ManagerCloudFormation Stack Outputs
OverviewVaultTerraform State Output
ResourcesComposing ServicesDeployment BucketStateAgent SkillsPython support
OverviewRuntimeGatewayMemoryBrowserCode InterpreterDev Mode
API Gateway Proxy
OverviewGeneral ConfigurationAuthenticationAPI KeysData SourcesResolversPipeline FunctionsSubstitutionsCachingDelta SyncCustom DomainWAFCLI Commands
Deploying SAM/CFN TemplatesWorkflow Tips
OverviewCreating PluginsCLI OutputCustom CommandsCustom VariablesExtending the Configuration schemaExtending and overriding configuration
OverviewDashboardAxiom
Overviewagent docsagent inspectagent setupagent skills installagent skills list / readdeploydeploy functiondeploy listdevdiffinfoinvokeinvoke localloginlogin awslogin aws ssologsmetricspackageplugin installplugin uninstallprintprunereconcileremoverollbackrollback functionusage
OverviewConcepts
OverviewMetricsTracesTroubleshoot
OverviewNode.jsPython
OutputsProviders
OverviewBranch DeploymentsPreview DeploymentsCustom ScriptsTestingPrivate PackagesNotificationsMono ReposDeploy in your own CI/CDBest PracticesTroubleshootingFAQ
OverviewSetupToolsAWS Integration
Serverless.yml Reference
Examples and TutorialsConfiguration Validation
  1. Usage
  2. Events
  3. REST API Gateway V 1

REST API Events (API Gateway v1)

The http event exposes a Lambda function at an endpoint of an Amazon API Gateway REST API (API Gateway v1). The Framework creates one REST API per service, or uses an existing REST API, with a resource and method for each event, and deploys it to a stage named after the service stage, or to the stage in provider.apiGateway.stage. Use a REST API when you need API keys and usage plans, request validation, mapping templates, private endpoints or resource policies; for lower cost and latency without those features, use an HTTP API. AWS compares the two in Choose between REST APIs and HTTP APIs.

This serverless.yml creates a REST API with a GET /hello endpoint:

# serverless.yml
service: my-service

provider:
  name: aws
  runtime: nodejs24.x

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get

With the default lambda-proxy integration, the handler receives the whole request and returns the whole response:

// handler.mjs
export const hello = async (event) => {
  return {
    statusCode: 200,
    headers: { 'x-custom-header': 'My Header Value' },
    body: JSON.stringify({ message: 'Hello World!' }),
  }
}

serverless deploy and serverless info print the endpoint under endpoints. The ServiceEndpoint stack output holds the stage URL:

endpoints:
  GET - https://abcdefghij.execute-api.us-east-1.amazonaws.com/dev/hello

HTTP endpoints

The http event takes path and method, as keys or as one string '<METHOD> /<path>':

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
      - http: GET /posts/{id}

method is get, post, put, patch, options, head, delete or any, in any case. The Framework removes a leading and a trailing / from path. A segment in braces, such as {id}, is a path parameter; {proxy+} matches the rest of the path.

Stage names may contain only letters, digits, - and _. A service with http events and a service stage with other characters stops with Invalid stage name <stage>: it should contains only [-_a-zA-Z0-9] for AWS provider if http event are present according to API Gateway limitation.

Integration types

The http event's integration sets how API Gateway passes requests to the backend. The names are case-insensitive:

integrationBackendRequest and response
lambda-proxy (default), aws-proxy, aws_proxyThe functionThe function gets the whole request and returns status code, headers and body.
lambda, awsThe functionRequest and response mapping templates and status code patterns in serverless.yml. See Lambda integration.
httpAn HTTP URL in request.uriMapping templates, as for lambda. See HTTP and HTTP proxy integrations.
http-proxy, http_proxyAn HTTP URL in request.uriThe request and response pass through.
mockNoneAPI Gateway answers from templates. See Mock integration.

With async: true and no integration, the integration is lambda. Use lambda-proxy unless you need mapping templates: it keeps the HTTP handling in your code.

Lambda proxy integration

With lambda-proxy, the function receives the request in API Gateway's proxy event format. This is a shortened event:

{
  "resource": "/posts/{id}",
  "path": "/posts/42",
  "httpMethod": "POST",
  "headers": {
    "content-type": "application/json",
    "Host": "abcdefghij.execute-api.us-east-1.amazonaws.com"
  },
  "queryStringParameters": { "draft": "true" },
  "pathParameters": { "id": "42" },
  "stageVariables": null,
  "requestContext": {
    "accountId": "123456789012",
    "stage": "dev",
    "requestId": "0f2431a2-6d2f-11e7-b799-5152aa497861",
    "identity": { "sourceIp": "203.0.113.10" }
  },
  "body": "{\"title\":\"Hello\"}",
  "isBase64Encoded": false
}

body is a string: parse a JSON body with JSON.parse(event.body). The function returns an object with statusCode, and optionally headers, multiValueHeaders, body (a string) and isBase64Encoded.

Catching exceptions in your Lambda function

With lambda-proxy, an unhandled error in the function makes API Gateway respond with status 502. To return another status, catch the error and return a response with that statusCode:

// handler.mjs
export const create = async (event) => {
  try {
    const post = JSON.parse(event.body)
    return { statusCode: 201, body: JSON.stringify(post) }
  } catch (error) {
    return {
      statusCode: 400,
      body: JSON.stringify({ message: 'The body must be valid JSON' }),
    }
  }
}

With the lambda integration, error messages map to status codes instead; see Status codes.

Enabling CORS

To answer browser CORS preflight requests for an endpoint, set the http event's cors to true:

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
          cors: true

The Framework adds an OPTIONS method to the path that returns the CORS headers. cors: true is the same as this object:

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
          cors:
            origin: '*'
            headers:
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
              - X-Amzn-Trace-Id
            allowCredentials: false

The cors object accepts these keys:

KeyDefaultDescription
origin'*'The allowed origin. A comma-separated list works like origins.
origins-A list of allowed origins; * in an origin is a wildcard (https://*.example.com). Replaces origin.
headersThe headers aboveThe allowed request headers; '*' allows any. A single string is accepted too.
methodsThe event's methodThe allowed methods. The Framework adds OPTIONS and the event's method.
allowCredentialsfalseSends Access-Control-Allow-Credentials: true. With false, the header is omitted.
maxAge-Seconds browsers may cache the preflight response (Access-Control-Max-Age), at least 1.
cacheControl-A Cache-Control header for the preflight response, so a CDN can cache it, such as 'max-age=600, s-maxage=600, proxy-revalidate'.

The browser accepts one Access-Control-Allow-Origin value. With several origins, the preflight response returns the request's Origin when it matches one of them:

cors:
  origins:
    - https://*.example.com
    - https://example2.com

When several events on the same path set cors, the Framework merges them into one OPTIONS method: it combines headers, methods and origins, and the last maxAge and cacheControl set win.

The OPTIONS method covers the preflight only. With lambda-proxy, the function must also return the CORS headers on the actual response:

// handler.mjs
export const hello = async (event) => {
  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: JSON.stringify({ message: 'Hello World!' }),
  }
}

With the lambda integration, the Framework adds Access-Control-Allow-Origin, and Access-Control-Allow-Credentials when allowCredentials is true, to the method's responses. That Access-Control-Allow-Origin value is static: with several origins, it holds all of them joined by commas, and browsers reject a response with more than one origin. With the lambda integration, set one origin; to serve several origins, use lambda-proxy and return the request's matching Origin from the function.

IAM authorization

To require callers to sign requests with AWS credentials, set the http event's authorizer to aws_iam:

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          authorizer: aws_iam

authorizer: { type: aws_iam } is the same. Callers need execute-api:Invoke on the method; see Control access to a REST API with IAM permissions.

HTTP endpoints with custom authorizers

A Lambda authorizer runs a function that decides whether API Gateway calls the endpoint. To use a function of the service, set authorizer to its name:

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          authorizer: authorizerFunc
  authorizerFunc:
    handler: handler.authorizerFunc

To use a function outside the service, set authorizer to its ARN:

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          authorizer: arn:aws:lambda:us-east-1:123456789012:function:Lambda-Name

The object form takes name or arn and these settings:

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          authorizer:
            name: authorizerFunc
            type: request
            resultTtlInSeconds: 0
            identitySource: method.request.header.Authorization, context.identity.sourceIp
  authorizerFunc:
    handler: handler.authorizerFunc
KeyDefaultDescription
name-A function of the service. With arn, the authorizer's name instead (default: the part of the ARN's function name after its last hyphen).
arn-The ARN of a Lambda function or a Cognito user pool. A CloudFormation intrinsic function needs name too.
typetokentoken, request, cognito_user_pools or aws_iam, in any case. A token authorizer reads one header; a request authorizer reads several identity sources.
identitySourcemethod.request.header.AuthorizationWhere API Gateway reads the identity; for request, a comma-separated list. A request authorizer with resultTtlInSeconds: 0 has no default.
identityValidationExpression-A regular expression the token identity must match before API Gateway invokes the authorizer.
resultTtlInSeconds300Seconds to cache the authorizer's result, 0 to 3600.
managedExternallyfalseWith true, the Framework doesn't create the permission that lets API Gateway invoke the function, for example for a function in another AWS account. The permission must exist before you deploy.

The Framework creates the authorizer on the REST API and, unless managedExternally is true, the invoke permission. AWS describes the authorizer's input and output in Use API Gateway Lambda authorizers.

Cognito user pool authorizers

To accept tokens from an Amazon Cognito user pool, set authorizer.arn to the user pool's ARN. scopes lists the OAuth scopes an access token must have:

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          authorizer:
            arn: arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_ZZZ
            scopes:
              - my-app/read

With lambda-proxy, the token's claims are in event.requestContext.authorizer.claims. To pass only some claims, use the lambda integration with claims; the function then gets them in event.cognitoPoolClaims. claims with lambda-proxy stops the deploy with Cognito claims can only be filtered when using the lambda integration type.

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          integration: lambda
          authorizer:
            arn: arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_ZZZ
            claims:
              - email
              - nickname

For a user pool declared under resources, reference its ARN with Fn::GetAtt and set name and type: COGNITO_USER_POOLS. Without name, the deploy stops with Please provide an authorizer name for authorizers of type COGNITO_USER_POOLS:

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          authorizer:
            name: MyAuthorizer
            type: COGNITO_USER_POOLS
            arn:
              Fn::GetAtt:
                - CognitoUserPool
                - Arn

resources:
  Resources:
    CognitoUserPool:
      Type: AWS::Cognito::UserPool
      Properties:
        UserPoolName: my-service-users

Share authorizer

To use one authorizer for endpoints in several services, for example on a shared REST API, create the authorizer once and reference its ID. Set the http event's authorizer.authorizerId and type:

functions:
  createUser:
    handler: users.create
    events:
      - http:
          path: /users
          method: post
          authorizer:
            type: COGNITO_USER_POOLS # TOKEN, REQUEST or COGNITO_USER_POOLS
            authorizerId:
              Ref: ApiGatewayAuthorizer # or the authorizer ID
            scopes: # Optional, COGNITO_USER_POOLS only
              - myapp/myscope

resources:
  Resources:
    ApiGatewayAuthorizer:
      Type: AWS::ApiGateway::Authorizer
      Properties:
        AuthorizerResultTtlInSeconds: 300
        IdentitySource: method.request.header.Authorization
        Name: Cognito
        RestApiId:
          Ref: ApiGatewayRestApi # the service's REST API, or the shared REST API ID
        Type: COGNITO_USER_POOLS
        ProviderARNs:
          - arn:aws:cognito-idp:${aws:region}:123456789012:userpool/us-east-1_ZZZ

With authorizerId, type: TOKEN and type: REQUEST make the method use a Lambda authorizer; scopes apply only with COGNITO_USER_POOLS. The Framework creates no authorizer or permission for these events.

When services on a shared REST API each set the same authorizer arn instead, each creates its own authorizer resource on the API, and they can clash. Share the authorizer by ID, or give each authorizer a unique name. A REST API has a default quota of 10 authorizers.

Operation ID

operationId sets the method's operation name, which SDK and OpenAPI code generators use as the method name:

functions:
  create:
    handler: users.create
    events:
      - http:
          path: users/create
          method: post
          operationId: createUser

Using asynchronous integration

With async: true, API Gateway invokes the function asynchronously and responds without waiting for the function to finish. Without integration, the integration is lambda, and API Gateway returns 200:

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          async: true # default: false

Setting API keys for your REST API

To require an API key on an endpoint, set the http event's private to true and list the keys under provider.apiGateway.apiKeys. Clients send a key's value in the x-api-key header. The Framework creates the keys, a usage plan for the stage and the links between them:

service: my-service

provider:
  name: aws
  apiGateway:
    apiKeys:
      - myFirstKey
      - ${sls:stage}-myFirstKey
      - name: myThirdKey
        value: ${ssm:/my-service/third-api-key}
      - value: ${ssm:/my-service/fourth-api-key} # CloudFormation names the key
        description: Api key description # Optional
        customerId: my-customer # Optional
        enabled: true # Optional, default: true
    usagePlan:
      quota:
        limit: 5000
        offset: 2
        period: MONTH
      throttle:
        burstLimit: 200
        rateLimit: 100

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: user/create
          method: get
          private: true

A string entry is a key name; AWS generates the value. serverless deploy and serverless info print the key values; --conceal hides them. Changing an entry's value replaces the key, which CloudFormation can't do while the key keeps a custom name: change the name too, or omit name and let CloudFormation name the key.

usagePlan.quota.period is DAY, WEEK or MONTH; limit, offset, burstLimit and rateLimit are integers of 0 or more.

For several usage plans, name each plan and group the keys under the plan names:

provider:
  name: aws
  apiGateway:
    apiKeys:
      - free:
          - myFreeKey
          - ${sls:stage}-myFreeKey
      - paid:
          - myPaidKey
          - ${sls:stage}-myPaidKey
    usagePlan:
      - free:
          quota:
            limit: 5000
            offset: 2
            period: MONTH
          throttle:
            burstLimit: 200
            rateLimit: 100
      - paid:
          quota:
            limit: 50000
            offset: 1
            period: MONTH
          throttle:
            burstLimit: 2000
            rateLimit: 1000

Each group's name must match a plan name under usagePlan; a group without a matching plan stops the deploy with API key "<name>" has no usage plan defined. Keys inside a group take the same forms as above: a name, or an object with name, value, description, customerId and enabled. quota and throttle are optional in every plan. Every plan applies to the service's stage, so an endpoint with private: true accepts a key from any plan.

API key source

API Gateway reads the API key from the x-api-key header by default (apiKeySourceType: HEADER). To take it from the usageIdentifierKey that a Lambda authorizer returns, set provider.apiGateway.apiKeySourceType to AUTHORIZER; see API key sources:

provider:
  name: aws
  apiGateway:
    apiKeySourceType: AUTHORIZER

Configuring endpoint types

provider.endpointType sets the REST API's endpoint type: EDGE (the default), REGIONAL or PRIVATE, in any case. Edge-optimized APIs route requests through Amazon CloudFront; regional APIs serve clients in the same Region; private APIs are reachable only from VPCs through interface VPC endpoints.

provider:
  name: aws
  endpointType: REGIONAL

For a private API, vpcEndpointIds lists the VPC endpoints to associate. API Gateway then creates a Route 53 alias for each, https://<rest-api-id>-<vpc-endpoint-id>.execute-api.<region>.amazonaws.com. vpcEndpointIds with endpointType set to EDGE or REGIONAL stops the deploy with VPC endpoint IDs are only available for private APIs. Without endpointType, the Framework ignores vpcEndpointIds and deploys an edge-optimized API, so set endpointType: PRIVATE with it.

provider:
  name: aws
  endpointType: PRIVATE
  vpcEndpointIds:
    - vpce-0123456789abcdef0

A private API also needs a resource policy that allows access from the VPC endpoints.

Request parameters

request.parameters declares the query string, header and path parameters of a method, for API Gateway's console tests and SDK generation. true makes a parameter required and false optional. When at least one parameter is required, the Framework attaches a request validator, so API Gateway rejects requests without it:

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/{id}
          method: post
          request:
            parameters:
              querystrings:
                url: true
              headers:
                foo: false
              paths:
                id: true

A path parameter must also appear in path, as {id} here.

To map a parameter to another value in the integration request, give required and mappedValue. The Framework applies mapped values for the lambda, http and http-proxy integrations. With lambda-proxy, it applies only the mapping of the X-Amz-Tenant-Id header, used by Lambda tenant isolation, and ignores the others:

functions:
  create:
    handler: posts.postDetail
    events:
      - http:
          path: posts/{id}
          method: get
          integration: lambda
          request:
            parameters:
              paths:
                id: true
              headers:
                custom-header:
                  required: true
                  mappedValue: context.requestId

AWS lists the values mappedValue accepts in parameter mapping.

Request schema validators

To validate request bodies, add a JSON Schema for each content type under request.schemas. The Framework creates an API Gateway model and a request validator; requests whose body doesn't match get 400. Content types without a schema aren't validated. API Gateway supports JSON Schema draft 4.

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          request:
            schemas:
              application/json: ${file(create_request.json)}

A sample create_request.json:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "required": ["username"],
  "properties": {
    "username": { "type": "string", "pattern": "^[a-zA-Z0-9]+$" }
  }
}

To name the model, use the object form with schema, name and description:

request:
  schemas:
    application/json:
      schema: ${file(create_request.json)}
      name: PostCreateModel
      description: 'Validation model for Creating Posts'

To reuse a model in several events, define it under provider.apiGateway.request.schemas and reference it by its key. Provider models are for the application/json content type:

provider:
  name: aws
  apiGateway:
    request:
      schemas:
        post-create-model:
          name: PostCreateModel
          schema: ${file(api_schema/post_add_schema.json)}
          description: 'A Model validation for adding posts'

functions:
  create:
    handler: posts.create
    events:
      - http:
          path: posts/create
          method: post
          request:
            schemas:
              application/json: post-create-model

Response streaming

REST APIs can stream responses from proxy integrations. Set the http event's response.transferMode to STREAM (default: BUFFERED):

functions:
  streamHandler:
    handler: handler.stream
    events:
      - http:
          path: stream
          method: get
          response:
            transferMode: STREAM

transferMode works with lambda-proxy and http-proxy only; with another integration the deploy stops with Property "response.transferMode" is supported only with AWS_PROXY (Lambda proxy) or HTTP_PROXY integrations. STREAM with async: true stops it with Property "response.transferMode: STREAM" cannot be combined with "http.async". A Node.js function streams by wrapping its handler with awslambda.streamifyResponse; see Response streaming for Lambda functions.

With proxy integrations, the Framework keeps only request.parameters, request.schemas (and request.uri for http-proxy) and response.transferMode; it removes other request and response keys and prints a warning.

Lambda integration

With integration: lambda, API Gateway transforms the request with a mapping template, invokes the function with the result, and maps the function's return value or error to the response. You configure the templates and status codes in serverless.yml.

Request templates

The Framework adds request templates for application/json and application/x-www-form-urlencoded. Both build an event with these properties: body, method, principalId, stage, cognitoPoolClaims, enhancedAuthContext, headers, query, path, identity, stageVariables and requestPath. A shortened event:

{
  "body": { "title": "Hello" },
  "method": "POST",
  "principalId": "",
  "stage": "dev",
  "cognitoPoolClaims": { "sub": "" },
  "enhancedAuthContext": {},
  "headers": { "Content-Type": "application/json" },
  "query": {},
  "path": { "id": "42" },
  "identity": { "sourceIp": "203.0.113.10" },
  "stageVariables": {},
  "requestPath": "/posts/{id}"
}

To add or replace templates, set request.template per content type. A template can also come from a file with ${file(template.vm)}:

functions:
  create:
    handler: posts.create
    events:
      - http:
          method: get
          path: whatever
          integration: lambda
          request:
            template:
              text/xhtml: '{ "stage" : "$context.stage" }'
              application/json: '{ "httpMethod" : "$context.httpMethod" }'

To read a query string parameter, use $input.params('name'). In a single-quoted YAML string, double the inner single quotes:

request:
  template:
    application/json: '{ "foo" : "$input.params(''bar'')" }'

A request to /dev/whatever?bar=123 then gives the function event.foo set to 123. To remove a default template, set it to null:

request:
  template:
    application/x-www-form-urlencoded: null

Pass-through behavior

request.passThrough sets what API Gateway does with a request whose Content-Type matches no template. The default is NEVER for the lambda integration; for http and mock the Framework sets none and API Gateway's default applies. A request without Content-Type counts as application/json.

ValuePassed through unchanged whenRejected with 415 Unsupported Media Type when
NEVERNeverNo template is defined, or Content-Type matches no template
WHEN_NO_MATCHContent-Type matches no templateNever
WHEN_NO_TEMPLATESNo template is definedTemplates are defined, but Content-Type matches none
request:
  passThrough: WHEN_NO_MATCH

AWS describes the options in integration passthrough behaviors.

Responses

response.headers sets response headers from integration response values or static values; API Gateway receives them as written, so a static value keeps its single quotes:

functions:
  create:
    handler: posts.create
    events:
      - http:
          method: get
          path: whatever
          integration: lambda
          response:
            headers:
              Content-Type: integration.response.header.Content-Type
              Cache-Control: "'max-age=120'"

response.template transforms the function's return value for application/json. This one returns the value as HTML:

response:
  headers:
    Content-Type: "'text/html'"
  template: $input.path('$')

Status codes

With the lambda integration, API Gateway picks the response status by matching the function's error message against a pattern per status code. The Framework adds these patterns:

Status codeSelected when
200The function returns without an error, or its error matches no other pattern (the default response)
400, 401, 403, 404, 422, 502The error message contains [<code>], such as [404] Not found
500The error message contains [500] or Process exited before completing request
504The error message contains [504], or ends with Task timed out after <n> seconds

To return 404, throw an error with [404] in its message:

// handler.mjs
export const hello = async (event) => {
  throw new Error('[404] Not found')
}

An error whose message contains none of these patterns, such as new Error('database unavailable'), gets the default response, so API Gateway returns 200. To return an error status, put one of the codes above in brackets in the message of every error the function throws, such as [500] database unavailable. See Handle Lambda errors in API Gateway.

To change the status codes, set response.statusCodes. Each code takes a pattern (a regular expression matched against the error message), and optionally template and headers. The code with pattern: '' is the default response; without one, the Framework adds 200 as the default:

functions:
  create:
    handler: posts.create
    events:
      - http:
          method: post
          path: whatever
          integration: lambda
          response:
            headers:
              Content-Type: "'text/html'"
            template: $input.path('$')
            statusCodes:
              201:
                pattern: '' # Default response
              409:
                pattern: '.*"statusCode":409,.*' # JSON response
                template:
                  application/json: $input.path("$.errorMessage")
                  application/xml: $input.path("$.body.errorMessage")
                headers:
                  Content-Type: "'application/json+hal'"

A code's template is a string for application/json, or a map of content types.

HTTP and HTTP proxy integrations

The http and http-proxy integrations send requests to an HTTP endpoint instead of a function. request.uri is required; without it the deploy stops with You need to set the request uri when using the HTTP_PROXY integration. (or HTTP). request.method sets the backend method (default: the event's method):

functions:
  proxy:
    handler: handler.proxy
    events:
      - http:
          path: v1/repository
          method: get
          integration: http-proxy
          request:
            uri: https://api.example.com/v1/repository
            method: get

Accessing private resources using VPC Link

To reach a backend in a VPC through a VPC link, set connectionType: vpc-link and the link's ID in connectionId. Without connectionId, the deploy stops with You need to set connectionId when using VPC_LINK connectionType.

functions:
  proxy:
    handler: handler.proxy
    events:
      - http:
          path: v1/repository
          method: get
          integration: http-proxy
          connectionType: vpc-link
          connectionId: a1b2c3
          request:
            uri: http://internal.example.com/v1/repository
            method: get

Mock integration

A mock integration answers from API Gateway without a backend, for example to stub an endpoint. The request template sets the status code and response.statusCodes maps it to a response:

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
          integration: mock
          request:
            template:
              application/json: '{"statusCode": 200}'
          response:
            template: $input.path('$')
            statusCodes:
              201:
                pattern: ''

Use an existing REST API

To add a service's endpoints to a REST API that another service or stack manages, set provider.apiGateway.restApiId and restApiRootResourceId (the ID of the API's / resource). restApiRootResourceId is required whenever restApiId is set; without it the deploy stops with Missing required "provider.apiGateway.restApiRootResourceId" property (needed if "provider.apiGateway.restApiId" is provided):

service: service-a

provider:
  name: aws
  apiGateway:
    restApiId: a1b2c3d4e5
    restApiRootResourceId: f6g7h8i9j0
    description: Some description # Optional: deployment description

functions:
  create:
    handler: posts.create
    events:
      - http:
          method: post
          path: /posts

The Framework creates the resources, methods and a deployment to the stage, but not the API. It doesn't change the stage's settings: provider.tags, provider.stackTags and provider.apiGateway.metrics aren't applied, and provider.tracing.apiGateway and provider.logs.restApi stop the deploy with an error.

The Framework creates a resource for each path segment from the root. When another service already created a parent path, CloudFormation can't create it again: list the existing resources in restApiResources, by path, with their IDs:

service: service-b

provider:
  name: aws
  apiGateway:
    restApiId: a1b2c3d4e5
    restApiRootResourceId: f6g7h8i9j0
    restApiResources:
      /posts: k1l2m3n4o5

functions:
  createComment:
    handler: posts.createComment
    events:
      - http:
          method: post
          path: /posts/{id}/comments

Share a REST API through stack exports

A service can create the REST API and export its IDs, and other services in the same Region import them with Fn::ImportValue:

service: my-api

provider:
  name: aws
  runtime: nodejs24.x

resources:
  Resources:
    MyApiGW:
      Type: AWS::ApiGateway::RestApi
      Properties:
        Name: MyApiGW

  Outputs:
    apiGatewayRestApiId:
      Value:
        Ref: MyApiGW
      Export:
        Name: MyApiGateway-restApiId
    apiGatewayRestApiRootResourceId:
      Value:
        Fn::GetAtt:
          - MyApiGW
          - RootResourceId
      Export:
        Name: MyApiGateway-rootResourceId
service: service-a

provider:
  name: aws
  apiGateway:
    restApiId:
      Fn::ImportValue: MyApiGateway-restApiId
    restApiRootResourceId:
      Fn::ImportValue: MyApiGateway-rootResourceId

functions:
  create:
    handler: posts.create
    events:
      - http:
          method: post
          path: /posts

Cross-stack exports work only within one Region; see Fn::ImportValue. The same pattern shares a WebSocket API through provider.apiGateway.websocketApiId; see WebSocket API events.

Resource policy

A resource policy controls who can invoke the API. Set its statements in provider.apiGateway.resourcePolicy:

provider:
  name: aws
  apiGateway:
    resourcePolicy:
      - Effect: Allow
        Principal: '*'
        Action: execute-api:Invoke
        Resource:
          - execute-api:/*/*/*
        Condition:
          IpAddress:
            aws:SourceIp:
              - '203.0.113.0/24'

Compression

To compress responses larger than a size, set provider.apiGateway.minimumCompressionSize in bytes, from 0 to 10485760. API Gateway then compresses payloads for clients that accept a supported encoding:

provider:
  name: aws
  apiGateway:
    minimumCompressionSize: 1024

Binary media types

To return binary data such as images, list the content types API Gateway treats as binary in provider.apiGateway.binaryMediaTypes:

provider:
  name: aws
  apiGateway:
    binaryMediaTypes:
      - '*/*'

functions:
  binaryExample:
    handler: binaryExample.handler
    events:
      - http:
          path: binary
          method: get

With lambda-proxy, the function sets the Content-Type header, returns the body base64-encoded and sets isBase64Encoded. This handler returns image.jpg from its own directory:

// binaryExample.mjs
import { readFile } from 'node:fs/promises'

export const handler = async () => ({
  statusCode: 200,
  headers: { 'Content-Type': 'image/jpeg' },
  body: (await readFile(new URL('./image.jpg', import.meta.url))).toString(
    'base64',
  ),
  isBase64Encoded: true,
})

Detailed CloudWatch metrics

To turn on detailed CloudWatch metrics for every method of the stage, set provider.apiGateway.metrics:

provider:
  name: aws
  apiGateway:
    metrics: true

AWS X-Ray tracing

To turn on X-Ray active tracing for the stage, set provider.tracing.apiGateway:

provider:
  name: aws
  tracing:
    apiGateway: true

With provider.apiGateway.restApiId, tracing.apiGateway stops the deploy with When external API Gateway resource is imported via "provider.apiGateway.restApiId", property "provider.tracing.apiGateway" is ineffective.

Tags, stack tags

The Framework tags the REST API's stage with provider.stackTags and provider.tags; tags wins for a key in both. It removes stage tags that are in neither:

provider:
  name: aws
  stackTags:
    stackTagKey: stackTagValue
  tags:
    tagKey: tagValue

Logs

To turn on logging for the REST API's stage, set provider.logs.restApi to true:

provider:
  name: aws
  logs:
    restApi: true

Without logs.restApi, the stage has no logging. With it, the Framework turns on access logs and execution logs. Access logs go to the log group /aws/api-gateway/<service>-<stage>, which keeps logs for provider.logRetentionInDays days when that is set. With provider.apiGateway.restApiId, logs.restApi stops the deploy with an error.

The object form changes these settings:

provider:
  name: aws
  logs:
    restApi:
      level: ERROR
      format: '{ "requestId":"$context.requestId", "ip": "$context.identity.sourceIp" }'
      accessLogging: true
      executionLogging: true
      fullExecutionData: false
KeyDefaultDescription
levelINFOExecution log level, INFO or ERROR. With executionLogging: false, the level is OFF.
formatThe default belowThe access log format.
accessLoggingtrueWrites access logs to the log group.
executionLoggingtrueWrites execution logs.
fullExecutionDatatrueLogs full request and response data in execution logs.
roleA role the Framework createsThe ARN of the IAM role API Gateway uses to write logs. See CloudWatch role for API Gateway logs.
roleManagedExternallyfalseWith true, the Framework doesn't set up the CloudWatch role.

The default access log format is:

requestId: $context.requestId, ip: $context.identity.sourceIp, caller: $context.identity.caller, user: $context.identity.user, requestTime: $context.requestTime, httpMethod: $context.httpMethod, resourcePath: $context.resourcePath, status: $context.status, protocol: $context.protocol, responseLength: $context.responseLength

CloudWatch role for API Gateway logs

API Gateway writes logs only with a CloudWatch Logs role set for the account, one per Region, shared by all APIs. With access logging on, the Framework sets it up with a custom resource:

  • By default, the Framework creates the IAM role serverlessApiGatewayCloudWatchRole with the AmazonAPIGatewayPushToCloudWatchLogs managed policy if it doesn't exist, and sets it as the account's CloudWatch role in the Region, replacing the role set before. serverless remove keeps the role and the setting.

  • With role, the Framework sets that role as the account's CloudWatch role, replacing the role set before:

    provider:
      name: aws
      logs:
        restApi:
          role: arn:aws:iam::123456789012:role/ApiGatewayCloudWatchLogsRole
    
  • With roleManagedExternally: true, the Framework leaves the setting alone; set the role yourself, for example in a separate account setup stack:

    provider:
      name: aws
      logs:
        restApi:
          roleManagedExternally: true
    

The custom resource acts when the stack first creates it; a later change to role doesn't update the account setting. With accessLogging: false, the REST API logs don't add the custom resource, so the account needs a CloudWatch role set already, unless provider.logs.websocket adds the custom resource for WebSocket API logs. The custom resource's Lambda function runs with the role in provider.iam.deploymentRole when that is set. The same restApi settings control the role setup for WebSocket API logs.

Disable default endpoint

Clients can call the API at its execute-api URL. To allow calls only through a custom domain, set provider.apiGateway.endpoint.disable to true:

provider:
  name: aws
  apiGateway:
    endpoint:
      disable: true

provider.apiGateway.disableDefaultEndpoint does the same; when both are set, endpoint.disable wins.

API name and stage name

The Framework names the REST API <stage>-<service>. With provider.apiGateway.shouldStartNameWithService: true, the name is <service>-<stage>; provider.apiName sets the name and takes precedence.

The API Gateway stage has the service stage's name. To deploy to a stage with another name, set provider.apiGateway.stage:

provider:
  name: aws
  apiGateway:
    stage: customStageName

provider.apiGateway.description sets the description of the REST API and of its deployments.

Timeout

API Gateway's default integration timeout is 29 seconds. To change it for every http event, set provider.apiGateway.timeoutInMillis; to change one event, set its timeoutInMillis, which wins. Both are integers of at least 50:

provider:
  name: aws
  endpointType: REGIONAL
  apiGateway:
    timeoutInMillis: 10000 # 10 seconds for all endpoints

functions:
  fetch:
    handler: handler.fetch
    events:
      - http:
          path: /posts/{id}
          method: get
  create:
    handler: handler.create
    events:
      - http:
          path: /posts
          method: post
          timeoutInMillis: 40000 # 40 seconds for this endpoint

Timeouts above 29 seconds need an increase of the integration timeout quota and are available only for REGIONAL and PRIVATE endpoint types; see API Gateway quotas. The Framework prints a warning when a function's timeout is longer than the integration timeout of one of its http events.

Security policy

A security policy sets the TLS versions and ciphers the REST API's default endpoint accepts. AWS's default is TLS_1_0 for edge-optimized and regional APIs and TLS_1_2 for private APIs. To choose one, set provider.apiGateway.endpoint.securityPolicy:

provider:
  name: aws
  apiGateway:
    endpoint:
      securityPolicy: SecurityPolicy_TLS13_2025_EDGE # TLS 1.3 only, edge-optimized APIs
      accessMode: strict

The policies depend on the endpoint type; AWS lists them in supported security policies:

  • TLS_1_0: TLS 1.0 to 1.3, every endpoint type.
  • TLS_1_2: TLS 1.2 and 1.3, regional and private APIs. Edge-optimized APIs don't accept it.
  • Enhanced policies, starting with SecurityPolicy_: for example SecurityPolicy_TLS13_2025_EDGE (TLS 1.3, edge-optimized) and SecurityPolicy_TLS13_1_3_2025_09 (TLS 1.3, regional and private).

Endpoint access mode

An enhanced SecurityPolicy_* policy requires endpoint.accessMode:

  • basic: API Gateway doesn't run the strict checks.
  • strict: API Gateway rejects requests whose Host header doesn't match the TLS Server Name Indication, or that come through another endpoint type. AWS recommends strict when your clients allow it; see endpoint access mode.

A custom domain has its own security policy; see Custom domains.

Related

  • REST API settings in the serverless.yml reference
  • HTTP API events: the httpApi event and API Gateway v2.
  • Custom domains
  • WebSocket API events
Edit this page
Prev HTTP (API Gateway v2)NextActiveMQ

Contents

  • REST API Events (API Gateway v1)
  • HTTP endpoints
  • Integration types
  • Lambda proxy integration
  • Catching exceptions in your Lambda function
  • Enabling CORS
  • IAM authorization
  • HTTP endpoints with custom authorizers
  • Cognito user pool authorizers
  • Share authorizer
  • Operation ID
  • Using asynchronous integration
  • Setting API keys for your REST API
  • API key source
  • Configuring endpoint types
  • Request parameters
  • Request schema validators
  • Response streaming
  • Lambda integration
  • Request templates
  • Pass-through behavior
  • Responses
  • Status codes
  • HTTP and HTTP proxy integrations
  • Accessing private resources using VPC Link
  • Mock integration
  • Use an existing REST API
  • Share a REST API through stack exports
  • Resource policy
  • Compression
  • Binary media types
  • Detailed CloudWatch metrics
  • AWS X-Ray tracing
  • Tags, stack tags
  • Logs
  • CloudWatch role for API Gateway logs
  • Disable default endpoint
  • API name and stage name
  • Timeout
  • Security policy
  • Endpoint access mode
  • Related

Related

GuidesPluginsExamplesSlack CommunitySupport