API design in Serverless architecture needs to consider stateless characteristics, cold start latency, and auto-scaling capabilities:
API design principles:
1. RESTful design
- Resource-oriented: Use nouns to represent resources, verbs to represent operations
- Unified interface: Use standard HTTP methods (GET, POST, PUT, DELETE)
- Version control: Version control through URL paths or request headers
2. Stateless design
- Session management: Use JWT Token or external storage to manage sessions
- Request independence: Each request contains all necessary information
- Idempotency: Ensure repeated requests don't produce side effects
3. Performance optimization
- Response caching: Use CloudFront, CDN to cache responses
- Batch operations: Support batch requests to reduce call count
- Asynchronous processing: Change long-running tasks to asynchronous processing
API Gateway configuration:
1. Routing configuration
- Path mapping: Configure mapping relationships between paths and functions
- Parameter validation: Use request validators to validate request parameters
- Rate limiting: Set API-level rate limiting policies
2. Authentication and authorization
- API Key: Use API Key for simple authentication
- Cognito: Integrate Cognito for user authentication
- Lambda Authorizer: Use Lambda functions for custom authorization
3. Response handling
- CORS configuration: Configure cross-origin resource sharing
- Error handling: Unified error response format
- Response transformation: Use mapping templates to transform response format
Best practices:
- API documentation: Use Swagger/OpenAPI to generate API documentation
- Monitoring and alerting: Monitor API call count, error rate, response time
- Security protection: Configure WAF to protect against common attacks
- Test coverage: Write API test cases to ensure interface quality
Candidates should be able to share API design experience and best practices from actual projects.