
FastAPI Interview Questions and Answers: Part 4 — Authentication, JWT, OAuth2 & Database
FastAPI Interview Questions and Answers: Part 4 — Authentication, JWT, OAuth2 & Database
In the previous parts, we covered FastAPI fundamentals, validation, asynchronous programming, Dependency Injection, WebSockets, background tasks, middleware, CORS, and testing.
Now we move into one of the most important areas of backend development:
Authentication, authorization, security, and database integration.
These topics are especially important because a real API is not only responsible for returning data. It must also make sure that users are allowed to access that data and that the application handles sensitive information safely.
1. How do you connect FastAPI with a database using SQLAlchemy?
FastAPI itself does not force us to use a particular database.
We can connect it with databases such as:
- PostgreSQL
- MySQL
- SQLite
- Other databases supported by appropriate libraries
A commonly used tool for SQL databases is SQLAlchemy.
SQLAlchemy is an ORM (Object Relational Mapper).
The word ORM may sound complicated, but the idea is simple.
Normally, a database understands SQL:
But in Python, we want to work with Python objects.
An ORM helps us work with database data using Python code.
A typical FastAPI + SQLAlchemy flow looks like this:
A simplified database dependency can look like:
Then an endpoint can receive the database session:
Here, Depends(get_db) tells FastAPI to provide a database session to the endpoint.
Why is this useful?
Instead of opening and closing database connections manually inside every API endpoint, we can centralize the database session management.
So the basic idea is:
SQLAlchemy allows FastAPI applications to interact with SQL databases using Python objects and queries.
The source material describes the same basic flow: create the engine/session, define models, use Dependency Injection for sessions, and perform database operations.
2. How do you manage database connections in FastAPI?
A database connection is like a phone call between your application and the database.
Your application needs to:
If we keep opening connections and never close them, eventually the application can run out of available database connections.
FastAPI's Dependency Injection system can help manage database sessions.
For example:
Then:
The important part is:
This ensures that the session is cleaned up after the request finishes.
Why use yield?
yield allows us to provide the database session to the endpoint and then run cleanup code afterward.
Conceptually:
This is important because database resources are limited.
The provided interview material specifically recommends managing database sessions through Dependency Injection and closing the session after use.
3. How do you handle database migrations in FastAPI using Alembic?
Imagine your application initially has this table:
Later, you decide that every user should also have:
You need to change the database structure.
You could manually modify the database, but this becomes difficult when multiple developers and environments are involved.
This is where Alembic is useful.
Alembic is a database migration tool commonly used with SQLAlchemy.
It keeps track of database schema changes.
For example:
Common Alembic workflow
Initialize Alembic:
Create a migration:
Apply the migration:
Why are migrations important?
Imagine three developers are working on the same project.
One developer adds a column.
Another developer adds a new table.
Without a proper migration system, keeping everyone's database structure synchronized becomes difficult.
Alembic provides a controlled history of database schema changes.
So:
Alembic helps us safely track and apply database structure changes over time.
The provided source specifically describes Alembic as a tool for managing SQLAlchemy schema changes and lists the initialization, revision, and upgrade workflow.
Authentication and Security
4. How can you secure FastAPI endpoints with OAuth2?
First, let's understand the problem.
Suppose we have:
We don't want every person on the internet to access someone's private profile.
The API needs to know:
Who is making this request?
OAuth2 provides a standard way of handling authorization flows.
FastAPI provides security utilities such as:
A simplified setup can look like:
Here:
tells FastAPI where the client can obtain the token.
The actual application still needs to:
- Verify the user's credentials.
- Generate a token.
- Send the token to the client.
- Validate the token on protected requests.
- Identify the user.
- Check whether the user has permission.
So OAuth2 is not simply "a login function."
It is part of a larger authentication and authorization system.
5. How do you implement OAuth2 with JWT authentication in FastAPI?
This is where OAuth2 and JWT often appear together.
Imagine a user logs in:
The client then sends the token with future requests:
The backend verifies the token before allowing access.
A simplified FastAPI example:
The important flow is:
Why JWT?
JWT allows information to be encoded into a token and signed so the server can verify its integrity.
A JWT generally looks like:
It has three parts:
The payload can contain claims such as:
However, JWT payload data should not be treated as secret merely because it is inside a JWT. Sensitive information should not be placed in the payload unless it is appropriately protected.
The source material describes OAuth2 + JWT as a common approach where the server validates credentials, generates a JWT, and verifies the token on future requests.
6. How can you implement JWT-based authentication in FastAPI?
A common implementation starts with OAuth2PasswordBearer.
Then a protected endpoint can request the token:
Let's understand what happens.
The client sends:
FastAPI extracts the token.
Then:
can validate the token and identify the user.
The complete flow is:
What happens if the token is invalid?
The API should reject the request rather than allowing the user to access protected information.
The source material specifically gives OAuth2PasswordBearer as the FastAPI mechanism for extracting the bearer token and then verifying it.
7. What are the important security considerations in FastAPI development?
Security is not one single feature.
A secure FastAPI application needs multiple layers of protection.
1. Authentication
First, verify who the user is.
Examples include:
- Password authentication
- OAuth2
- Access tokens
2. Authorization
After identifying the user, check what they are allowed to do.
For example:
3. Input validation
Never blindly trust data coming from the client.
For example:
If the API expects an integer, it should reject the invalid input.
Validation also helps reduce the risk of certain attacks when combined with proper database/query practices.
4. Password hashing
Never store user passwords as plain text.
Instead, use a strong password hashing algorithm.
Conceptually:
During login:
5. Encryption
Sensitive information should be protected both during transmission and, where appropriate, while stored.
HTTPS is essential for protecting data in transit.
6. Security headers
Security-related HTTP headers can provide additional browser-side protections.
Examples include:
7. Rate limiting
Suppose someone sends:
to your login endpoint in a short period.
That can put unnecessary load on the server and may be part of an abuse or brute-force attempt.
Rate limiting can restrict how many requests a client can make within a given time period.
The provided source identifies authentication, authorization, input validation, encryption, security headers, password hashing, CORS, and rate limiting as important security considerations.
8. How do you implement role-based authorization in FastAPI?
Authentication tells us:
Who is the user?
Authorization tells us:
What is the user allowed to do?
Suppose our application has two roles:
An admin might be allowed to:
A normal user might only be allowed to:
This is called Role-Based Access Control (RBAC).
A simplified flow is:
For example:
But:
The important point is that authorization must be enforced by the backend.
Hiding an "Admin" button in React is not security.
A user can still manually send the API request.
So:
Frontend checks improve the user experience; backend checks provide the actual security boundary.
The provided interview material explicitly describes authorization as controlling access based on user roles and permissions.
9. How does a protected FastAPI endpoint work?
Let's connect everything together.
Suppose we have:
This endpoint should only be accessible to administrators.
The request might look like:
The backend then performs several checks.
Step 1 — Is there a token?
Step 2 — Is the token valid?
Step 3 — Who is the user?
The backend identifies the user from the validated token.
Step 4 — What is the user's role?
For example:
Step 5 — Does that role have permission?
If the user is authenticated but doesn't have permission:
The complete protected API flow is:
This is the basic architecture behind many real-world protected APIs.
10. How do you secure passwords in a FastAPI application?
One of the biggest mistakes a backend developer can make is storing passwords like this:
If the database is compromised, the actual passwords are immediately exposed.
Instead, applications should store a password hash.
For example:
When the user logs in:
If they match, authentication succeeds.
Important distinction
Hashing is not the same as encryption.
Encryption is designed so that data can later be decrypted using a key.
Password hashing is designed as a one-way process for verification.
For password storage, use a password-hashing algorithm designed for passwords rather than inventing your own hashing method.
The provided source specifically recommends strong password hashing such as bcrypt for securely storing passwords.
The Complete Picture
At this point, our FastAPI application has evolved considerably.
Part 1
Part 2
Part 3
Part 4
Now:
A typical real-world request can therefore look like:
That is the important connection between authentication, authorization, FastAPI, and databases.
The next and final part can move into the production side of FastAPI: performance optimization, rate limiting, large file uploads, caching, global exception handling, project architecture, and real-world system-design questions. The provided interview material places these among the experienced-level topics.
Join Techsnap Creators
Share your knowledge and earn ??
Want to showcase your tech expertise and get rewarded for your insights? Join the Techsnap creator network!
Write insightful blogs, stay ahead of industry trends, and grow your professional brand while helping others in the community.
Ready to make an impact?

Comments