Permissions determine what an authenticated user is allowed to do.
For example:
- An admin can delete users.
- A normal user cannot delete users.
- If a user does not have the required permission, the API should return 403 Forbidden.
In FastAPI, permissions can be implemented using dependencies.
Admin Permission Check
First, create a dependency that checks whether the current user has the admin role.
from fastapi import Depends, HTTPException
def admin_required(
user=Depends(get_current_user)
):
if user["role"] != "admin":
raise HTTPException(
status_code=403,
detail="Permission denied"
)
return user
Using the Permission in a Route
Now we can protect an endpoint so that only administrators can access it.
@app.delete("/users/{user_id}")
def delete_user(
user_id: int,
user=Depends(admin_required)
):
return {
"message": "User deleted"
}
The complete flow is:
Request
โ
get_current_user
โ
admin_required
โ
Check user role
โ
Admin?
โโโโโโโโโดโโโโโโโโ
Yes No
โ โ
Allow 403 Error
โ
Delete User
Understanding the Code
get_current_user
user=Depends(get_current_user)
This gets the currently authenticated user.
The admin_required function then receives that user.
For example:
{
"id": 1,
"name": "John",
"role": "admin"
}
Checking the Role
if user["role"] != "admin":
This checks whether the user’s role is admin.
If the role is not, admin the request is rejected.
Returning a 403 Error
raise HTTPException(
status_code=403,
detail="Permission denied"
)
HTTP status code 403 means that the user is authenticated but does not have permission to perform the requested action.
Protecting the Endpoint
user=Depends(admin_required)
This makes admin_required a dependency of the delete_user endpoint.
Therefore, the endpoint will only execute if the permission check succeeds.
Successful Response
When an administrator calls the endpoint:
{
"message": "User deleted"
}
Permission Flow
A typical permission system works like this:
User Login
โ
Authentication
โ
Get Current User
โ
Check User Role
โ
Check Permission
โ
Allow / Deny Request
Authentication answers:
Who is the user?
Permissions answer:
What is the user allowed to do?
Summary
In this topic, we learned:
- Permissions control access to API operations.
- FastAPI dependencies can be used to implement permission checks.
- An
admin_requireddependency can restrict an endpoint to administrators. - Unauthorized actions can return 403 Forbidden.
- Permissions can be applied directly to API routes using
Depends().
This approach allows different users to have different levels of access within a FastAPI application.