Skip to content

16 Authorization

DodaTech 1 min read

title: Authorization in FastAPI REST APIs weight: 26 date: 2026-06-28 lastmod: 2026-06-28 description: Implement role-based and permission-based authorization in FastAPI using dependency injection with reusable auth dependencies for admin and resource ownership checks. tags: [api-development, fastapi]


Authorization in FastAPI uses dependency injection to create reusable permission checkers that verify role requirements and resource ownership, composing auth dependencies for granular access control.

```python
from fastapi import Depends, HTTPException, status

# Role-based authorization dependency
def require_role(required_role: str):
    async def role_checker(current_user: models.User = Depends(get_current_user)):
        if current_user.role != required_role and current_user.role != "admin":
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Role {required_role} required"
            )
        return current_user
    return role_checker

# Usage: require_admin = require_role("admin")
@router.get("/admin/dashboard")
def admin_dashboard(admin: models.User = Depends(require_role("admin"))):
    return {"message": f"Welcome admin {admin.username}"}

# Resource ownership check
async def get_post_or_404(post_id: int, db: Session = Depends(get_db)):
    post = db.query(models.Post).filter(models.Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    return post

def require_owner:
    async def owner_checker(
        post: models.Post = Depends(get_post_or_404),
        current_user: models.User = Depends(get_current_user)
    ):
        if post.author_id != current_user.id and current_user.role != "admin":
            raise HTTPException(status_code=403, detail="Not the owner")
        return post
    return owner_checker

@router.delete("/posts/{post_id}")
def delete_post(post: models.Post = Depends(require_owner())):
    db.delete(post)
    db.commit()
    return {"message": "Post deleted"}

What's Next

Now learn about testing with HTTPX and Pytest in Building REST APIs with FastAPI.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro