FastAPI – How to use Depends #14

Posted by


FastAPI is a modern web framework for building APIs with Python. One of its key features is the ability to easily define and use dependencies using the Depends class. Dependencies are reusable blocks of logic that can be injected into route functions to provide additional functionality, such as authentication, database connections, or data validation.

In this tutorial, we will explore how to use Depends in FastAPI to create a simple API with authentication using JWT tokens. We will create a dependency to extract and verify JWT tokens from incoming requests, and then use it in a route to authenticate users.

First, make sure you have FastAPI and PyJWT installed. You can install them using pip:

pip install fastapi
pip install pyjwt

Let’s start by creating a new FastAPI app in a file called main.py:

from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
import jwt

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, "secret_key", algorithms=["HS256"])
        return payload.get('sub')
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token has expired")
    except jwt.JWTError:
        raise HTTPException(status_code=401, detail="Invalid token")

@app.get("/users/me")
def read_users_me(current_user: str = Depends(get_current_user)):
    return {"username": current_user}

In the code above, we import the necessary components from FastAPI and PyJWT, and define a new FastAPI app. We also create an OAuth2PasswordBearer instance to handle token extraction from incoming requests.

Next, we define a dependency called get_current_user that takes a token as input. Inside the dependency, we use PyJWT to decode and verify the token. If the token is valid, we return the subject (sub) from the token payload. If the token has expired or is invalid, we raise an HTTPException.

Finally, we create a route /users/me that depends on get_current_user. This route will return the username of the authenticated user.

To test our API, we can run the FastAPI app using uvicorn:

uvicorn main:app --reload

Now, we can make a GET request to http://localhost:8000/users/me with a valid JWT token in the Authorization header:

curl -X GET http://localhost:8000/users/me -H "Authorization: Bearer your_jwt_token"

If the token is valid, the API will return a JSON response with the username of the authenticated user. If the token is invalid or has expired, an error response will be returned.

In this tutorial, we have learned how to use Depends in FastAPI to create dependencies for handling authentication logic. Dependencies are a powerful feature of FastAPI that make it easy to add reusable and modular functionality to your API routes.

0 0 votes
Article Rating

Leave a Reply

29 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@artemshumeiko
4 days ago

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

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

@romanryaboshtan9270
4 days ago

молодец, спасибо что объясняешь

@endlinkkk3951
4 days ago

Оч хорошая подача, вот прям как надо, все по делу)

@Ratmirsh
4 days ago

Возможно лучшее объяснение Depends не только в русскоязычном ютубе, но и в англоязычном

@1klassavgfan
4 days ago

Хаю хай АртёмГай !

@ahmadum
4 days ago

Благодарю

@hovharoyan3262
4 days ago

Огромное спасибо тебе Артем

@zion4d
4 days ago

в классе AuthGuard метод init не нужен

@nurkenspashev
4 days ago

ахах, хайю-хай свами Артем гей)))

@maximkoltsov9833
4 days ago

Столкнулся с моментом, когда скопировал код блока базы данных с кучи разных примеров как мне надо, но так и не разобрался что как работает)) Не понимал конструкцию async_generator, потом заметил, что с ней работают через depends в эндпоинтах. Писал тестовый скрипт на выполнение в консоли без эндпоинта, теперь понял в чем ошибался 😅 Полезное видео, спа

@SeliverstovMusic
4 days ago

Увидел Depends в чужом коде. Оказалось удобно. Отличный разбор, спасибо =)

@stassolovyov2297
4 days ago

17:27. Зачем библиотеку обозвал так?))

@alexeymatveev9031
4 days ago

Спасибо Вам большое, долго пытаюсь, уже почти месяц понять работу авторизации на fastapi и вот именно этого знания мне не хватало, чтобы пройти вперед.

@borzxoYT
4 days ago

Когда сказал родителям, что занимаешься программированием и они заходят в твою комнату чтобы проверить: 17:27

@eugene_fed
4 days ago

Чтобы не прыгать между двумя скриптами можно навести стрелку на вкладку скрипта (где имя файла указано) и нажать ПКМ, далее выбрать Split Right (или прожать Alt+H по-умолчанию). Ну и спокойно слева видеть свой код а справа – код библиотеки. Либо два куска одного и того же файла. И самому удобно, и демонстрировать тем более.

@dimuha82
4 days ago

По авторизации это получается аналог permission_classes в DRF, если я правильно понял

@adammason482
4 days ago

Спасибо за урок!

@RunBull
4 days ago

спасибо большое за ролики, нашёл работу благодаря ним

@скриптослав
4 days ago

Братан, харош! Давай-давай, вперед! Контент в кайф! Можно еще? Ваще красавчик! Можно вот этого вот почаще?

@romanbush5164
4 days ago

Супер полезный видос🙂

29
0
Would love your thoughts, please comment.x
()
x