Create a simple authenticate API with Python FastAPI

Photo by Samson on Unsplash

Authenticate the user credential is a must step for any API services.

By the end of this post, you can create an authenticate API that looks like this

I. Hash the real password before save to database:

Previously, we’re doing like this :

Faked hashed_password

Now, we will hash the password using the bycrypt library.

bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher, and presented at USENIX in 1999.[1] Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with increasing computation power.

To install bcrypt library in python, simply

pipenv install bcrypt

And now the code for create new user will look like:

Hashed password with bcrypt

II.Check the input password for authenticate API matching

Check the password matched or not

To be able to do this, we use bcrypt.checkpw from the bcrypt library.

III.Create a token object response if the username and password is correct

1.Define Token Schemas in schemas.py

2.Create an access token by using jwt library

Utilize the jwt library in python by installing it:

pipenv install pyjwt

Then define a method that create an access token from the hashed_password in the database

IV.Wrap altogether and define the authenticate api from main.py

Wrap it altogether to create authenticate API

The below method will validate the username and password, then return the access_token in the response if the username and password is correct.

To run the server, simply click on the run button from IDE, or by command line:

uvicorn main:app --reload

Please check the full sourcecode from github .

Happy coding~~~

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store