Top Libraries and Extensions for FastAPI [2024]

Posted by


FastAPI is a modern web framework for building APIs with Python that is becoming increasingly popular due to its high performance and ease of use. In this tutorial, we’ll take a look at some of the top libraries and extensions for FastAPI that can help you build even more powerful and efficient APIs in 2024.

  1. FastAPI-jwt-auth

FastAPI-jwt-auth is a library that provides JWT authentication support for FastAPI applications. JWT (JSON Web Tokens) is a popular method for securely transmitting information between parties as a JSON object. This library makes it easy to add JWT authentication to your FastAPI API, allowing you to authenticate users and protect your endpoints from unauthorized access.

To use FastAPI-jwt-auth, you can install it via pip:

pip install fastapi_jwt_auth

You can then import the necessary components in your FastAPI application and add JWT authentication to your endpoints. For example, you can use the JWTAuthentication class to protect a specific endpoint:

from fastapi_jwt_auth import AuthJWT

@router.get("/protected")
async def protected_route(auth: AuthJWT = Depends()):
    credentials = auth.get_jwt()

    # Access the protected data
    # ...

    return {"message": "Protected route accessed successfully"}
  1. FastAPI-caching

FastAPI-caching is a library that provides simple and efficient caching support for FastAPI applications. Caching can help improve the performance of your API by storing the results of expensive computations or database queries and returning them quickly when the same request is made again.

To use FastAPI-caching, install it via pip:

pip install fastapi-caching

You can then import the Cache class in your FastAPI application and use it to set up caching for specific endpoints or functions. For example, you can use the cached decorator to cache the results of a function:

from fastapi_caching import Cache

cache = Cache()

@router.get("/cached")
@cache.cached()
async def cached_route():
    # Compute some expensive result
    result = ...

    return result
  1. FastAPI-rate-limit

FastAPI-rate-limit is a library that provides rate limiting support for FastAPI applications. Rate limiting can help protect your API from abuse by limiting the number of requests that can be made within a certain time period. This can help prevent things like DDoS attacks or excessive usage by individual users.

To use FastAPI-rate-limit, install it via pip:

pip install fastapi-rate-limit

You can then import the RateLimiter class in your FastAPI application and use it to set up rate limiting for specific endpoints or functions. For example, you can use the rate_limit decorator to limit the number of requests that can be made to a specific endpoint:

from fastapi_rate_limit import RateLimiter

limiter = RateLimiter()

@router.get("/limited")
@limiter.limit("5 per minute")
async def limited_route():
    # Handle the request
    # ...

    return {"message": "Request processed successfully"}
  1. FastAPI-async-mysql

FastAPI-async-mysql is a library that provides asynchronous MySQL database support for FastAPI applications. Using asynchronous database access can help improve the performance of your API by allowing multiple queries to be executed concurrently without blocking the event loop.

To use FastAPI-async-mysql, install it via pip:

pip install fastapi-async-mysql

You can then import the necessary components in your FastAPI application and use them to execute asynchronous database queries. For example, you can create a connection pool and execute a query using the mysql_pool function:

from fastapi_async_mysql import AsyncMySQLClient

client = AsyncMySQLClient()

# Create a connection pool
await client.create_pool()

# Execute a query
result = await client.execute("SELECT * FROM table")

# Process the query result
# ...

In this tutorial, we’ve covered some of the top libraries and extensions for FastAPI that can help you build more powerful and efficient APIs in 2024. By using these libraries, you can add features like JWT authentication, caching, rate limiting, and asynchronous database access to your FastAPI applications, making them even more robust and high-performing.

0 0 votes
Article Rating
28 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@artemshumeiko
1 month ago

💡 Попробуй онлайн-тренажёр для подготовки к техническому собеседованию: https://clck.ru/3B5gwP 💡

Забирай роадмап изучения самого востребованного фреймворка на Python – FastAPI здесь: https://t.me/ArtemShumeikoBot

@user-tt9xr9tb1i
1 month ago

есть БЕСПЛАТНЫЙ МАТЕРИАЛ В МОЁМ ПЛАТНОМ КУРСЕ))), забавно звучит)))

@lethnisoff
1 month ago

SQLModel было бы интересно увидеть у тебя на канале

@user-uf2es4px9l
1 month ago

Использовал SQL model, мне понравилось. Но при связывании моделей были сложности и приходилось использовать sa_kwargs. Не критично, но получилось что работая в sql model, докидываешь существенную часть кода как бы на алхимии.

@maybe_ghost_
1 month ago

Давай видео по SQLModel заранее спасибо

@Guiscardqq
1 month ago

решение большинства проблем с авторизацией – authlib (вроде BSD-3 лицензия ограничений не накладывает)

@user-yc7rq8iu1g
1 month ago

Добрый день! Спасибо большое за видео, подчерпнула для себя новую информацию. Если есть такие запросы и личное желание, было бы здорово увидеть видео с подробным сравнением фреймворков. На одном из собеседований задали такой вопрос, как ни странно. В частности сравнение FastAPI и Django (DRF).

@AleksandrChernovIT
1 month ago

Артём привет! Возможно ли докупить доступ в группу, после оплаты стандартного тарифа? Пока хотел бы в фоне пройти самостоятельно курс, а по необходимости докупить вход в группу. Спасибо за FastAPI!

@begenFys
1 month ago

Спасибо за такой подробный ролик! Очень интересно послушать про slowapi, fastapi_profiler и, конечно, аутентификацию, их много не бывает)

@iJaVolo
1 month ago

Хочу видос про аутентификацию

@pavloukrainets
1 month ago

Хотелось бы больше узнать про внутреннюю комуникацию меж-ду микросервисами (не отложенные задачи как в прошлых видео, а незамедлительное взаимодействие), какие существует техники, какие из них наиболее популярны и востребованы на реальных проектах и как их реализовать в интеграции с FastAPI.

@vog25
1 month ago

Артём, можете пожалуйста подсказать, какие три проекта я могу сделать для портфолио с помощью FastAPI?

@alexfinner2129
1 month ago

Очень жду кастомную аутентификацию

@user-dk8sq
1 month ago

,

@user-dk8sq
1 month ago

Привет Артем, в платном курсе по фатсапи ты rest api пишешь?

@shokha94
1 month ago

+ Ждём с нетерпением подробный видос про авторизацию, jwt, рефреш, аксес токены, role & permission management 😊

@user-in6ys6hu8x
1 month ago

@artemshumeiko
Для авторизации и аутентификации отлично подходит кейклок, можешь на него обзор сделать, там есть все что душе угодно)

@nobrainfearless3437
1 month ago

Что насчёт Tortoise ORM?

@spirit3064
1 month ago

Артем добрый день, а как вы думаете на нынешнем рынке IT нужны новые бэкэндеры или уже все места закончились?)

@timhunter2477
1 month ago

хочу обзор на SQL Model