What is Security?
Security, authentication, and authorization in APIs typically involve several moving parts:- Authentication: Verifying who the user is
- Authorization: Verifying what the user can do
- API Keys: Simple secret tokens for authentication
- OAuth2: Industry-standard protocol for authorization
- JWT Tokens: JSON Web Tokens for stateless authentication
Security Utilities in FastAPI
FastAPI provides multiple security utilities that integrate seamlessly with your API and automatic interactive documentation:OAuth2 Tools
OAuth2PasswordBearer
OAuth2 flow for authentication using a bearer token obtained with a password
OAuth2PasswordRequestForm
Dependency class to collect username and password as form data
OAuth2AuthorizationCodeBearer
OAuth2 flow using authorization code (for third-party login)
SecurityScopes
Handle OAuth2 scopes for fine-grained permissions
HTTP Authentication
HTTPBasic
HTTP Basic authentication with username and password
HTTPBearer
HTTP Bearer token authentication
HTTPDigest
HTTP Digest authentication (stub for custom implementation)
API Key Authentication
APIKeyQuery
API key authentication via query parameter
APIKeyHeader
API key authentication via HTTP header
APIKeyCookie
API key authentication via cookie
How FastAPI Security Works
FastAPI’s security utilities work through the dependency injection system:1
Define the security scheme
Create an instance of a security class (e.g.,
OAuth2PasswordBearer, HTTPBasic)2
Use as a dependency
Use the security instance as a dependency in your path operations with
Depends()3
Automatic validation
FastAPI automatically validates the security credentials and extracts the token/key
4
OpenAPI integration
Your API documentation automatically shows the security requirements with a “Authorize” button
Example: Basic OAuth2 Setup
Here’s a minimal example showing how FastAPI security works:OAuth2PasswordBearertells FastAPI that tokens will be obtained from a/tokenendpoint- When you call
/items/, FastAPI checks for anAuthorization: Bearer <token>header - The token is automatically extracted and passed to your function
- The
/docspage shows an “Authorize” button for testing
Security Standards
FastAPI security utilities follow industry standards:- OAuth2: RFC 6749
- HTTP Basic Auth: RFC 7617
- HTTP Bearer: RFC 6750
- OpenAPI Security Schemes: OpenAPI 3.1.0 Specification
What’s Next?
Now that you understand the basics, let’s build a real authentication system:First Steps
Create your first OAuth2 endpoint with password flow
Get Current User
Build a dependency to get the currently authenticated user
OAuth2 with JWT
Implement proper JWT token authentication with password hashing
OAuth2 Scopes
Add fine-grained permissions with OAuth2 scopes
Remember: Security is complex. These tutorials provide a solid foundation, but always review your security implementation carefully and consider consulting security experts for production systems.