Skip to main content
In this lesson, you will learn how to leverage an access token to fetch the current user directly from your database. Initially, the implementation of the get_current_user function calls the verify_access_token function, which only extracts and returns the user ID from the token data. Enhancing this logic to automatically retrieve the full user record allows you to attach the complete user object to any path operation, enabling more complex business logic in your endpoints. Below, you’ll find the initial implementation demonstrating the basic structure using the verify_access_token function and the get_current_user dependency.

In a production application, remember that the token data only contains the user ID. To work with the entire user object, you must extend this implementation to query your database.

Extended Implementation: Retrieving the User Object from the Database

In a real-world scenario, after verifying the token, you will want to query your database to fetch the complete user record. The extended version below demonstrates how to import your database session dependency, query the user model, and return the full user object.

Using the Current User Dependency in Route Operations

The following examples demonstrate how to integrate the get_current_user dependency within your route operations. Notice that the dependency now returns the full user object (referred to as current_user). This enhancement eliminates the need to repeatedly query the database in each endpoint.

Console Output Verification

When you run your application, you should see console output similar to the following: INFO: Started server process [12328]
INFO: Application startup complete.
sanjeev@gmail.com
INFO: 127.0.0.1:59999 - “POST /posts HTTP/1.1” 201 Created
This output confirms that the current_user dependency correctly retrieves and prints the user’s email, ensuring that user-specific data is readily available for any subsequent business logic in your endpoints.
By returning the complete user object via the get_current_user dependency, your FastAPI application can efficiently access and utilize user-specific information throughout your route operations. This approach streamlines the management of authentication and user authorization in your API.

Watch Video