#100DaysOfCode Day 8: Structuring the API with Blueprint and Flask-RESTful

Richard Russell
Cold Brew Code
Published in
2 min readMay 12, 2020

At first, I wanted to leave this small Flask REST API project and start a new one. But then, I decided that because I have already reached this stage, I might as well finish it to perfection!

[Note, you can follow the tutorial made by Paurakh Sharma Humagain in this link]

In yesterday’s article, we were able to store our movies — the James Dean trilogy! — into a MongoDB database. Today, I am going to learn how to structure my flask application in a more maintainable way.

We are going to learn two ways of structuring the Flask application:

  • Blueprint: it is used to structure the Flask application into different components, making it easier to structure the application based on different functionality.’
  • Flask-RESTful: extension of Flask that helps with building REST APIs quickly and following the REST architecture.

Structuring Flask API using Blueprint

First, create a new directory named resources inside your main project folder. Inside this directory, create a new Python file name movie.py, which will have the following code:

From the code above, you can see that the code is exactly the same as the app.py file. Because of that, your app.py should look like the following:

That’s all you have to do to use Blueprint and structure your Flask application.

Structuring Flask API using Flask-RESTful

To structure your app with Flask-RESTful, install the flask-restful package using pipenv. Remember, make sure you are not installing a typo!

Now, update your movie.py so that it can be used on flask-restful. You can copy the following code:

As you can see, flask-restful uses a Class-based syntax. Now, let’s register these endpoints by creating a new file titled routes.py inside the resources directory and add the following to it:

After we have defined the functions to initialize the routes, let’s revise our app.py to the following:

Enough for today

Surprisingly, I was able to get through today’s tutorial fairly quickly. Sure, there were bugs here and there; however, there were the same bugs that I faced with a few days ago. Hence, I was able to quickly fix these bugs. Also, I began to fully understand the structure of the code, which is a plus point from consistency :)

Remember: stay consistent!

--

--

Richard Russell
Cold Brew Code

i like to write about code. i also like cold brew coffee.