Sub topic 5
Designing routes and path parameters
This chapter assumes you can read the version 2.0 event format from the previous chapters, and that you know what a route, an integration and a stage are. Here you will learn how API Gateway chooses a route for a request, how to design route patterns, and how your handler can use the result.
What a route is
A route is a method and a path pattern joined by a space. The whole string is the route key.
GET /items/{id}Each route points to one integration, which here is a Lambda function. When a request arrives, API Gateway picks the best matching route and invokes that route's integration. It does not invoke Lambda if no route matches.
Three kinds of route keys exist:
| Route key | Meaning |
|---|---|
| `GET /items` | A fixed method and a fixed path |
| `GET /items/{id}` | A path with a parameter that matches exactly one path segment |
| `ANY /items` | Any HTTP method on that path |
| `GET /files/{proxy+}` | A greedy parameter that matches the rest of the path |
| `$default` | A catch-all for requests that match no other route |
Path parameters
A parameter is a name in braces, such as {id}. It matches one segment between slashes. GET /items/{id} matches /items/42 but not /items/42/reviews and not /items.
A greedy parameter ends in +, as in {proxy+}. It matches one or more segments and must be the last part of the path. For GET /files/{proxy+}, the request /files/2026/report.pdf gives the proxy parameter the value 2026/report.pdf.
In the version 2.0 event, parameters arrive in pathParameters, a dictionary keyed by the name you chose:
{
"routeKey": "GET /files/{proxy+}",
"rawPath": "/files/2026/report.pdf",
"pathParameters": {"proxy": "2026/report.pdf"}
}The pathParameters key is missing, or null, when the route has no parameters. A route such as GET /items has none, so event["pathParameters"]["id"] would raise an error there. Use event.get("pathParameters") or {} in any code shared by several routes.
How API Gateway picks a route
More than one route can match a request. API Gateway chooses the most specific one:
- An exact path match, such as
GET /items/new. - A path with single-segment parameters, such as
GET /items/{id}. - A greedy path, such as
GET /items/{proxy+}. - The
$defaultroute.
For the same path, an explicit method beats ANY. So GET /items wins over ANY /items for a GET request, and ANY /items handles every other method.
This precedence is what lets GET /items/new coexist with GET /items/{id}. Without it, the word new would be captured as an id.
Designing a route set
Good routes follow the same conventions as any HTTP API:
- Use plural nouns for collections, such as
/itemsand/orders. - Put identifiers in the path, as in
/orders/{orderId}. - Express nesting only where the child cannot exist without the parent, such as
/orders/{orderId}/lines/{lineId}. Deep nesting makes routes brittle. - Put filters, sorting and paging in the query string, such as
/items?color=red&limit=20. These are not part of the route key and never affect which route matches. - Let the method carry the action: GET reads, POST creates, PUT or PATCH changes, DELETE removes.
- Name parameters descriptively (
orderId, notid) when a path has more than one.
One function or many
You can map each route to its own function, or map many routes to one function. Both work, and each has costs.
| Approach | Advantage | Cost |
|---|---|---|
| One function per route | Small packages, least-privilege roles per route, separate metrics | More resources to manage, more cold starts overall |
| One function for related routes | Fewer resources, warm instances shared across routes | Larger package, one broad role, handler must dispatch |
A middle path works well for most APIs: one function per resource, such as all /items routes in one function.
Dispatching on the route key in a handler
When one function serves several routes, branch on event["routeKey"]. A dictionary of route keys to functions scales better than a chain of if statements. The route key already contains the method, so you never need to inspect it separately.
import json
def respond(status, body):
return {
"statusCode": status,
"headers": {"content-type": "application/json"},
"body": json.dumps(body),
}
def get_item(event):
return respond(200, {"id": event["pathParameters"]["id"]})
def get_review(event):
params = event["pathParameters"]
return respond(200, {"item": params["id"], "review": params["reviewId"]})
def get_file(event):
return respond(200, {"path": event["pathParameters"]["proxy"]})
ROUTES = {
"GET /items/{id}": get_item,
"GET /items/{id}/reviews/{reviewId}": get_review,
"GET /files/{proxy+}": get_file,
}
def handler(event, context):
route_fn = ROUTES.get(event["routeKey"])
if route_fn is None:
return respond(404, {"message": "Not found"})
return route_fn(event)
if __name__ == "__main__":
sample = {
"routeKey": "GET /files/{proxy+}",
"rawPath": "/files/2026/report.pdf",
"pathParameters": {"proxy": "2026/report.pdf"},
}
print(handler(sample, None))The route key in the event is the pattern, not the concrete URL. A request for /items/42 has the route key GET /items/{id}. The concrete values are in pathParameters, and the raw URL path is in rawPath.
The $default route has the route key $default. Because your own handler has no method in that key, read the method from event["requestContext"]["http"]["method"].
Declaring routes in SAM
In AWS SAM, each route is an HttpApi event on the function. Placeholders in Path use the same brace syntax.
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
Events:
GetItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items/{id}
Method: GET
GetReview:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items/{id}/reviews/{reviewId}
Method: GET
GetFile:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /files/{proxy+}
Method: GETEach event creates one route and the permission that lets API Gateway invoke the function.
Common mistakes
- Route key mismatch. The key in your handler must match the deployed key exactly, including parameter names. Renaming
{id}to{itemId}in the template without updating the handler givesKeyErroror a 404 from your own dispatch table. - Trailing slashes.
/itemsand/items/are different paths. Define the form your clients use, and test the other form. - Case sensitivity. Paths are case sensitive, so
/Itemsdoes not match/items. - Root path with greedy routes.
/{proxy+}requires at least one segment, so it may not catch/. Test the root path explicitly. - Stage prefix. For a named stage such as
prod,rawPathincludes the stage name (/prod/items/42), but the route key does not. Dispatch onrouteKey, notrawPath, and the stage prefix never matters.
Exercise
An API defines the routes GET /orders/{orderId}, GET /orders/recent and ANY /orders/{proxy+}. Which route handles GET /orders/recent, which handles GET /orders/17, and which handles DELETE /orders/17/lines/3? What is the pathParameters value in the last case?
Show answer
GET /orders/recent goes to the exact route GET /orders/recent, because an exact match beats a parameter route. GET /orders/17 goes to GET /orders/{orderId}, because a single-segment parameter is more specific than the greedy route. DELETE /orders/17/lines/3 goes to ANY /orders/{proxy+}, because no other route matches that method and depth. Its pathParameters is {"proxy": "17/lines/3"}.