Create a simple authenticate API with Python FastAPI

Donald Le
2 min readMar 16, 2020
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 :

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:

II.Check the input password for authenticate API matching

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

--

--

Donald Le

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