This guide explains how to create and manage API endpoints with Stelvio. You'll learn
how to define routes, connect them to Lambda functions, and understand the different
organizational patterns available to you.
Creating an API
Creating an API Gateway in Stelvio is straightforward. You start by defining your API
instance:
The name you provide will be used as part of your API's URL and for identifying it in
the AWS console.
API Configuration
For production use cases, you can configure your API Gateway with additional settings:
fromstelvio.aws.apigatewayimportApi# Basic API with default settingsapi=Api('my-api')# API with custom domainapi=Api('my-api',domain_name='api.example.com')# API with custom stage nameapi=Api('my-api',stage_name='production')# API with edge-optimized endpointapi=Api('my-api',endpoint_type='edge')# API with all custom settingsapi=Api('my-api',domain_name='api.example.com',stage_name='production',endpoint_type='edge')
Available configuration options:
domain_name (optional): Custom domain name for your API. See Custom Domains section below.
stage_name (optional): Stage name for your API deployment. Defaults to "v1".
endpoint_type (optional): API Gateway endpoint type - "regional" (default) or "edge". See Endpoint Types below.
Endpoint Types
Choose the right endpoint type based on your use case:
"regional": Best for applications primarily serving users in a specific AWS region. Lower latency for regional users and simpler configuration.
"edge": Best for applications serving global users. Uses CloudFront to cache responses at edge locations worldwide for better global performance.
Stage names help organize different versions or environments of your API:
# Development stageapi=Api('my-api',stage_name='dev')# Production stage api=Api('my-api',stage_name='production')# Version-based stagingapi=Api('my-api',stage_name='v2')
The stage name becomes part of your API URL: https://api-id.execute-api.region.amazonaws.com/{stage_name}/
Defining Routes
Stelvio provides a clean, intuitive way to define API routes. The basic pattern is:
api.route(http_method,path,handler)
Let's look at each component:
http_method: The HTTP verb for this route ('GET', 'POST', etc.)
path: The URL path for this endpoint ('/users', '/orders/{id}', etc.)
handler: Lambda function handler or path to it
Here's a complete example:
fromstelvio.aws.apigatewayimportApiapi=Api('my-api')# Basic routeapi.route('GET','/users','functions/users.index')# Route with path parameterapi.route('GET','/users/{id}','functions/users.get')# Route with different HTTP methodapi.route('POST','/users','functions/users.create')# Deployment happens automatically when routes or configurations change.
Add all routes before accessing API properties
All routes and authorizers must be added before accessing any API properties
like api.resources, api.api_arn, or api.invoke_url. These properties
trigger resource creation, after which modifications are not allowed.
# Correct - add all routes firstapi=Api('my-api')api.route('GET','/users','functions/users.handler')api.route('POST','/users','functions/users.create')# Now safe to access properties# Wrong - will raise RuntimeErrorapi=Api('my-api')api.route('GET','/users','functions/users.handler')arn=api.api_arn# Triggers resource creationapi.route('POST','/users','functions/users.create')# RuntimeError!
HTTP Methods
Stelvio supports all standard HTTP methods. You can specify them in several ways:
fromstelvio.aws.apigatewayimportApiapi=Api('my-api')# Single method (case insensitive)api.route('GET','/users','functions/users.index')api.route('get','/users','functions/users.index')# Multiple methods for one endpointapi.route(['GET','POST'],'/users','functions/users.handler')# Any HTTP methodapi.route('ANY','/users','functions/users.handler')api.route('*','/users','functions/users.handler')# Alternative syntax
Lambda function Integration
Stelvio offers flexible ways to connect your routes to Lambda functions. The handler
path in your route definition can have two formats:
Where everything before :: is the path to the folder of your lambda function, and
everything after is the relative path to file and function name within that folder.
Previous versions of Stelvio automatically generated routing code when multiple routes pointed to different functions in the same file. This behavior has been removed.
These now create separate Lambda functions. To share a single Lambda, use an explicit Function instance or point both routes to the same handler function.
The textbook pattern of Serverless architecture is to have one function per endpoint.
# These routes create one Lambda function eachapi.route('GET','/users','functions/users.index')# Lambda function 1api.route('POST','/users','functions/users.create_user')# Lambda function 2
In complex applications, you might end up with an enormous number of AWS resources if you follow this pattern.
Also, the code above will duplicate the entire file (functions/users.py) in each Lambda function.
This behaviour can lead to more cold starts, because Lambda functions 1 and 2 are technically separate from each other.
So, hitting the GET endpoint won't automatically pre-warm the Lambda (2) for the POST endpoint.
For practical reasons, you might want to have a single Lambda function handling different endpoints. You can do so by creating a custom routing logic:
This will deploy the same Lambda function to multiple routes.
Similarly, creating functions in the Api.route method using the short cut uses the same logic:
api=Api("MyApi",)# Next line creates ONE functionapi.route("get","/a","functions/api.handler_1")# Next line creates ONE functionapi.route("get","/b","functions/api.handler_2")# Next line re-uses function "functions/api.handler_2"api.route("get","/c","functions/api.handler_2")
Lambda Configuration
The above samples will create functions with default configuration. If you want to
customize Lambda function settings like memory size, timeout or
runtime settings, you have several options:
Through FunctionConfig class
# In this example we configure custom memory size and timeoutapi.route("GET","/users",FunctionConfig(handler="functions/users.index",memory=512,timeout=30,),)
Through dictionary FunctionConfigDict.
FunctionConfigDict() is typed dict so all your keys and values will be typed checked
if you use IDE or mypy or other type checking tool.
# In this example we configure custom memory size and timeoutapi.route("GET","/users",{"handler":"functions/users.index","memory":512,"timeout":30,},)
Through keyword arguments
# In this example we configure custom memory size and timeoutapi.route("GET","/users","functions/users.index",memory=512,timeout=30,)
Passing function instance as a handler:
You can create lambda function yourself and pass it to the route as a handler.
# Defined in separate variable.users_fn=Function("users-function",handler="functions/users.index",memory=512,)api.route("GET","/users",users_fn)# Inline. api.route("GET","/orders",Function("orders-function",folder="functions/orders",handler="handler.index",),)
Warning
When you create function yourself Stelvio will not generate any routing code for
you, you're responsible for it.
Remember
Each instance of Function creates new lambda function so if you want to
use one function as a handler for multiple routes
you need to store it in a variable first.
Only One Configuration per Function
When multiple routes use same function (identified
by the same file for Single-File Functions
and by the same folder (src) for
Folder-Based Functions), the function
should be configured only once. If other route uses same function it shares config
from the route that has config.
If you provide configuration in multiple places for the same function , Stelvio will
fail with an error message. This ensures clear and predictable behavior.
To configure a shared function, either configure it on its first use or create a
separate Function instance and reuse it across routes. (As shown above in point 4.)
A note about handler format for Folder-based functions
The :: format (folder/path::file.function_name) for folder-based functions is a
convenient shorthand specific to API Gateway routes. However, you can still create
folder-based functions using configuration options. Here are all the ways to define
a folder-based function:
# Using FunctionConfig classapi.route("POST","/orders",FunctionConfig(folder="functions/orders",handler="function.handler",),)# Using configuration dictionaryapi.route("POST","/orders",{"src":'functions/orders',"handler":"function.handler",},)# Using keyword argumentsapi.route("POST","/orders",folder="functions/orders",handler="function.handler",)# Using Function instanceapi.route("GET","/orders",Function("orders-function",folder="functions/orders",handler="handler.index",),)
Authorization
Stelvio supports AWS API Gateway authorizers to secure your API endpoints. You can use Lambda-based authorizers (Token and Request types), Cognito User Pools, or AWS IAM authorization.
By default, routes are public. To protect routes, either add auth to specific routes or set a default authorizer:
api=Api('my-api')# Without default auth - routes are publicapi.route('GET','/health','functions/api/health.handler')# Public# With default auth - routes are protected by defaultjwt_auth=api.add_token_authorizer('jwt-auth','functions/authorizers/jwt.handler')api.default_auth=jwt_authapi.route('GET','/users','functions/api/users.handler')# Protectedapi.route('GET','/public','functions/api/public.handler',auth=False)# Public
Token Authorizers (JWT, OAuth)
Token authorizers validate bearer tokens (like JWTs) from a single source, typically the Authorization header. They're ideal for OAuth 2.0 or JWT-based authentication.
fromstelvio.aws.apigatewayimportApiapi=Api('my-api')# Add TOKEN authorizerjwt_auth=api.add_token_authorizer('jwt-auth','functions/authorizers/jwt.handler',identity_source='method.request.header.Authorization',# defaultttl=600,# cache duration in seconds)# Use authorizer on routesapi.route('GET','/protected','functions/api/protected.handler',auth=jwt_auth)
Your authorizer Lambda function receives the token and returns an IAM policy:
Request authorizers can validate using multiple sources (headers, query strings, context) and have access to the full request. They're useful for complex authentication schemes.
api=Api('my-api')# Add REQUEST authorizer with multiple identity sourcesrequest_auth=api.add_request_authorizer('custom-auth','functions/authorizers/custom.handler',identity_source=['method.request.header.X-API-Key','method.request.querystring.token','method.request.header.X-Session-ID',],ttl=300,)api.route('POST','/orders','functions/api/orders.handler',auth=request_auth)
Your authorizer Lambda receives the full request context:
Clients must include a valid Cognito JWT token in the Authorization header.
Configuration options:
name: Unique authorizer name within the API
user_pools: List of Cognito User Pool ARNs
ttl: Cache TTL in seconds (default: 300)
OAuth 2.0 Scopes
For fine-grained access control, use OAuth 2.0 scopes with Cognito authorizers. Different routes can require different scopes even when using the same authorizer.
api=Api('my-api')cognito_auth=api.add_cognito_authorizer('cognito-auth',user_pools=['arn:aws:cognito-idp:us-east-1:123456789:userpool/us-east-1_ABC123'],)# Different routes require different scopesapi.route('GET','/users','functions/api/users_list.handler',auth=cognito_auth,cognito_scopes=['users:read'],)api.route('POST','/users','functions/api/users_create.handler',auth=cognito_auth,cognito_scopes=['users:write'],)api.route('DELETE','/users/{id}','functions/api/users_delete.handler',auth=cognito_auth,cognito_scopes=['admin'],)
How scopes work:
Configure scopes in your Cognito User Pool settings
When users authenticate, Cognito issues an access token containing their scopes
API Gateway validates the token and checks if it contains at least ONE of the required scopes
If the token lacks required scopes, API Gateway returns 403 Forbidden
The scopes are included in the JWT access token payload:
Set a default authorizer to protect all routes automatically. Routes can override by specifying a different auth value:
api=Api('my-api')jwt_auth=api.add_token_authorizer('jwt-auth','functions/authorizers/jwt.handler')api.default_auth=jwt_auth# Uses jwt_auth (default, unless specified otherwise)api.route('GET','/users','functions/api/users.handler')# Override with different authorizerrequest_auth=api.add_request_authorizer('custom','functions/authorizers/custom.handler')api.route('POST','/admin','functions/api/admin.handler',auth=request_auth)# Make public (overrides default)api.route('GET','/public','functions/api/public.handler',auth=False)# Use IAM auth (overrides default)api.route('POST','/internal','functions/api/internal.handler',auth='IAM')
Public Routes
Routes are public by default. To protect all routes, assign an authorizer to api.default_auth. To make specific routes public when using a default authorizer, set auth=False on those routes:
# Without default auth - routes are publicapi=Api('my-api')api.route('GET','/health','functions/api/health.handler')# With default auth - use auth=False for public routesapi=Api('my-api')jwt_auth=api.add_token_authorizer('jwt-auth','functions/authorizers/jwt.handler')api.default_auth=jwt_authapi.route('GET','/users','functions/api/users.handler')# Protectedapi.route('GET','/public','functions/api/public.handler',auth=False)# Public
Route-Level Authorization
Each route can specify its own authorization:
api=Api('my-api')jwt_auth=api.add_token_authorizer('jwt-auth','functions/authorizers/jwt.handler')admin_auth=api.add_request_authorizer('admin-auth','functions/authorizers/admin.handler')# Different auth per route (no default auth)api.route('GET','/users','functions/api/users.handler',auth=jwt_auth)api.route('POST','/admin','functions/api/admin.handler',auth=admin_auth)api.route('POST','/internal','functions/api/internal.handler',auth='IAM')api.route('GET','/public','functions/api/public.handler')# Public
CORS
CORS (Cross-Origin Resource Sharing) allows browser-based applications to call your API from different domains. Without CORS, browsers block requests from web apps hosted on different domains than your API.
allow_origins: Single origin string (e.g., "*" or "https://example.com"). Multiple origins (list) not supported - see "Why Single Origin Only?" section below.
allow_methods: String or list of HTTP methods (default: "*"). Examples: "GET", ["GET", "POST"], or "*" for all.
allow_headers: String or list of header names (default: "*"). Examples: "Content-Type", ["Content-Type", "Authorization"], or "*" for all.
allow_credentials: Boolean to allow cookies and authentication headers (default: False). When True, you must specify a specific origin (cannot use "*").
max_age: Optional integer for preflight cache duration in seconds (e.g., 3600 for 1 hour).
expose_headers: Optional list of response headers accessible to browser JavaScript (e.g., ["X-Custom-Header"]).
Lambda Response Headers
Lambda must return CORS headers
For REST API v1, your Lambda functions must return CORS headers in successful (2XX) responses. OPTIONS methods and error responses (4XX/5XX) are handled automatically by Stelvio.
Stelvio generates a stlv_resources.py file with a CORS helper:
fromstlv_resourcesimportResourcesimportjsondefhandler(event,context):# Option 1: Use the helper methodreturn{"statusCode":200,"headers":Resources.cors.get_headers(),"body":json.dumps({"message":"Success"})}# Option 2: Access individual propertiesreturn{"statusCode":200,"headers":{"Access-Control-Allow-Origin":Resources.cors.allow_origin,"Content-Type":"application/json",},"body":json.dumps({"message":"Success"})}# Option 3: Merge with other headersreturn{"statusCode":200,"headers":{**Resources.cors.get_headers(),"Content-Type":"application/json","X-Custom-Header":"value",},"body":json.dumps({"message":"Success"})}
What Stelvio Creates
When CORS is enabled, Stelvio automatically creates:
OPTIONS methods: Mock integration for preflight requests (no Lambda invocation)
Gateway responses: CORS headers on 4XX/5XX error responses
stlv_resources.py: Generated helper with Resources.cors.get_headers() method
Why Single Origin Only?
API Gateway REST API v1 uses static configuration for CORS:
OPTIONS methods: MOCK integration responds with fixed CORS headers (configured at deployment)
Gateway responses (4XX/5XX): Static CORS headers set at deployment time
Both are configured when you deploy your API and cannot dynamically inspect the incoming Origin header to select from multiple allowed origins.
Gateway responses handle errors that occur before reaching Lambda (auth failures, throttling, rate limits, etc.) and cannot be made dynamic—they're an API Gateway feature, not something you can customize with code.
For most use cases, choose one of these approaches:
Use "*" if you don't need credentials (allows all origins)
Use specific origin if you need credentials or want to restrict to one domain
Custom Domains
Connecting a custom domain to your API Gateway is essential for production applications. Stelvio simplifies this process by allowing you to specify a custom domain name when creating your API.
To set up a custom domain, you need to provide the domain_name parameter when creating your API instance:
As outlined in the DNS guide, this app configuration will assume you have set up a DNS provider for your app like so:
fromstelvioimportStelvioAppfromstelvio.cloudflare.dnsimportCloudflareDnsfromstelvio.aws.dnsimportRoute53Dnsapp=StelvioApp("my-app",dns=Route53Dns("your-route53-zone-id"),# use Route53 on AWS,# dns=CloudflareDns("your-cloudflare-zone-id") # use Cloudflare as DNS provider,# other configurations...)
Behind the scenes, Stelvio will take care of the following high level tasks:
Make sure the API Gateway responds to requests made to api.example.com
Create a TLS certificate for api.example.com
Create a DNS record that resolves api.example.com to the API Gateway endpoint
Custom Domains in Environments
Obviously, one domain can only be attached to one ApiGateway. If you want to use the same custom domain in multiple environments, you need to assign different subdomains for each environment.
One way of doing this is to use the environment name as a subdomain. For example, if your custom domain is api.example.com, you can use dev.api.example.com for the development environment and prod.api.example.com for the production environment.
You can achieve this by using the context().env variable in your API definition:
@app.rundefrun()->None:# With custom domainapi=Api("todo-api",domain_name=CUSTOM_DOMAIN_NAMEifcontext().env=="prod"elsef"{context().env}.{CUSTOM_DOMAIN_NAME}")api.route("GET","/a",handler="functions/todos.get")
This way, the API Gateway will respond to requests made to dev.api.example.com in the development environment and prod.api.example.com in the production environment.
Exposing API Gateway along with other resources
If you want to expose an API Gateway along with other resources, such as S3 Buckets, you can use the Router component.
Behind the Scenes
When you set a custom domain, Stelvio will automatically create the following resources:
AcmValidatedDomain: Stelvio component with the following Pulumi resources:
pulumi_aws.apigateway.DomainName: Represents the custom domain in API Gateway.
stelvio.dns.Record: A DNS record that points your custom domain to the API Gateway endpoint.
pulumi_aws.apigateway.BasePathMapping: Maps the custom domain to your API Gateway stage.
Customization
The Api component supports the customize parameter to override underlying Pulumi resource properties. For an overview of how customization works, see the Customization guide.