Building your first Flask REST API with MongoDB and JWT

Designed by pch.vector / Freepik

In this article, I am going to explain you step-by-step how to build your first Web API app. I assumed you already know the basic of python and you already have Python and an IDE installed.

The following topics will be covered in this article:
-Flask
-MongoDB
-RESTful API
-JWT

Flask

Flask is a lightweight and an easy-to-use web framework that provides a way to quickly build a backend for your application.
First, install Flask framework using pip with the following command:

pip install flask

Build a Basic Application

In order to build a basic flask application create a new file called “app.py” and use the following code:

our basic app.py

In the first lines of the code we imported the Flask class and then we create an instance of it. Next, we use the @app.route decorator, the parameter we send set what URL should trigger the following function. The “if” statements will be true when our model is being run directly (and not being imported by something else).

Finally, the run() function will run the application, set the debug parameter to true will reload the application on code changes which will help us during the development process.

Run the application by running the “app.py” file, then you should see:

Let’s open the http://localhost:5000/ URL in browser to make sure everything work, you should see:

MongoDB

MongoDB is one of the most popular NoSQL databases. In SQL databases the data stored in table format. In MongoDB the data stores in JSON format. JSON forms a tree data structure and the individual records are known as ‘documents’.

We choose to work with MongoDB because the data represent in the same way that application do. It is also more flexible and easy to scale.

Do the following steps to create your MongoDB database:
1. Go to https://cloud.mongodb.com and create an account.
2. Click on “Create a cluster” button.
3. The default settings should be fine. Scroll down and type in a name for your cluster.

4. Click on “Connect” and then click “Add Your Current IP Address” to be able to connect MongoDB from your computer.
5. Set a username and password and click on “Create Database User”.

6. Click on “Choose a connection method” and then “connect your application”.
7. Choose python and copy your connection string, save it for later.

8. Now let’s go to “Collection” and click on “Add My Own Data”.
9. Choose database and collection name and click on “ Create”.

We are now going to use PyMongo library which allows interaction with the MongoDB database through Python.
So, let’s install it:

pip install pymongo

Now, let’s import pymongo and configurate our mongoDB database

We use the MongoClient class to make a connection, we then choose our relevant database and collection (as we defined at MongoDB Cloud).

BASIC OF REST:

Rest is a very common Architectural Style for an application program interface.

Rest offers a stateless protocol and standard operation which provides many advantages such as fast performance, reliability, scalability, separation between client and server and more.

In Rest the server data represented as resources, the customer can access the resources by using web URIs (Uniform Resource Identifiers) and HTTP.

Here are some basic things you should know:

HTTP Methods
POST — use to create a new resources.
GET — use to read (or retrieve) a representation of a resource.
PUT — use to update a resource.
DELETE — use to delete a resource.

Endpoints
GET Example.com/api/v1/users — will retrieve a list of users
POST Example.com/api/v1/users — will create a new user
DELETE Example.com/api/v1/users/1 — will delete user with id 1

Status code
RESTful APIs use the Status-Line part of an HTTP response message to inform clients of their request’s overarching result.
1xx: Informational
2xx: Success
— The client’s request was successfully.
3xx: Redirection — The client must take some additional action in order to complete their request.
4xx: Client Error — Error at client request.
5xx: Server Error — Error at the server side.

Register

After we talked about RESTful we can now make our first function that will handle the registration logic and let us add new users to our database.

There are some serval basic things we want to do when we add new users. We need to make sure that the username not already registered. If the username is new we can create the new user, if not we will return an error code.

As we learn about RESTful, while register a new user we create a new resource, so this request should be a POST method. The HTTP Status code we use are: Code 201 mean “created” and Code 409 describe that was a conflict and the request could not be completed.

We also want to hash the password of the user before we save it in our database. This way, if someone will get access to our database data he won’t be able to know the user’s real password, but we still be able to confirm that the password the user send is the same as the one we have in the database.

Login And JWT

To be able to secure the transmitting to the API and identifying the user without any private credentials we will use JWT (Json Web Token)

How do JWT work?
JWT is basically a string that is encrypted on the server-side and holds information about the user, when the user successfully login with their credentials we can return a JWT. The user will attach the JWT to his next requests. Then, we decrypt the JWT on the server-side and we can identify the user.

Why JWT?
JWT has a lot of benefits, unlike Server-side sessions, You don’t need to store the session identifier in a database and check them in each request. It’s meant JWT let us identify users with less database request. Read more about JWT benefits here:

[add link]

Install flask_jwt_extended in order to use JWT:

pip install flask_jwt_extended

Now let’s write some code:

We define a secret key that will use to sign the token, Your secret key should never be given to anyone else. You need to keep this key a secret. We also need to define for how long the given token will be valid, for that we use the JWT_ACCESS_TOKEN_EXPIRES and set it for 1 day.
At first we check if the user exists and if the password are correct. Then, we use create_access_token() to create a JWT with the current username (There are ways to store more data inside the JWT).

On successful request you should get this:

Getting the profile

After we logged in and got the JWT (access token), we need to use it so we could know what user make a request, it will help us to know what data we should return and if the user have the access to that data.

The @jwt_required decorator means that this function will work only if the user will attach the JWT to the request. get_jwt_identity() function takes the JWT check if it’s valid and return the identity data we saved before. It allows us to get the username data from the database. If you try to go to profile route with out JWT, you will get a 401 status code which means unauthorized.

Full Code

This is the full code combined for our Flask web-api app using flask, MongoDB and JWT.

I hope this article was helpful, there are of course a lot of things could be improve in this code like data validation, more error checking and so on, I just want to show you the basic.

There are lots of other topics worth reading and getting to know more, you will find lots of documentation online (and here in Medium).