You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -853,6 +853,130 @@ You can instruct API Gateway handler to use a custom serializer to best suit you
853
853
}
854
854
```
855
855
856
+
### Split routes with Router
857
+
858
+
As you grow the number of routes a given Lambda function should handle, it is natural to split routes into separate files to ease maintenance - That's where the `Router` feature is useful.
859
+
860
+
Let's assume you have `app.py` as your Lambda function entrypoint and routes in `users.py`, this is how you'd use the `Router` feature.
861
+
862
+
=== "users.py"
863
+
864
+
We import **Router** instead of **ApiGatewayResolver**; syntax wise is exactly the same.
865
+
866
+
```python hl_lines="4 8 12 15 21"
867
+
import itertools
868
+
from typing import Dict
869
+
870
+
from aws_lambda_powertools import Logger
871
+
from aws_lambda_powertools.event_handler.api_gateway import Router
@router.get("/") # /users, when we set the prefix in app.py
953
+
def get_users() -> Dict:
954
+
...
955
+
956
+
@router.get("/<username>")
957
+
def get_user(username: str) -> Dict:
958
+
...
959
+
960
+
# many other related /users routing
961
+
```
962
+
963
+
964
+
#### Trade-offs
965
+
966
+
!!! tip "TL;DR. Balance your latency requirements, cognitive overload, least privilege, and operational overhead to decide between one, few, or many single purpose functions."
967
+
968
+
Route splitting feature helps accommodate customers familiar with popular frameworks and practices found in the Python community.
969
+
970
+
It can help better organize your code and reason
971
+
972
+
This can also quickly lead to discussions whether it facilitates a monolithic vs single-purpose function. To this end, these are common trade-offs you'll encounter as you grow your Serverless service, specifically synchronous functions.
973
+
974
+
**Least privilege**. Start with a monolithic function, then split them as their data access & boundaries become clearer. Treat Lambda functions as separate logical resources to more easily scope permissions.
975
+
976
+
**Package size**. Consider Lambda Layers for third-party dependencies and service-level shared code. Treat third-party dependencies as dev dependencies, and Lambda Layers as a mechanism to speed up build and deployments.
977
+
978
+
**Cold start**. High load can diminish the benefit of monolithic functions depending on your latency requirements. Always load test to pragmatically balance between your customer experience and development cognitive load.
979
+
856
980
## Testing your code
857
981
858
982
You can test your routes by passing a proxy event request where `path` and `httpMethod`.
0 commit comments