DEV Community

Cover image for Create an API in Flask - Part One
Graham Morby
Graham Morby

Posted on • Updated on

Create an API in Flask - Part One

Coming from PHP to Python has been a blast! I'm loving it, the way code is written out and the indentation just makes Python so much easier to read and update. So after using Laravel for so long I decided to try a web API in Python and my library of choice was Flask.

Full Flask docs can be found here: https://flask.palletsprojects.com/en/2.0.x/foreword/#what-does-micro-mean

So what do we need to get started?
So I'm going to use Windows, PyCharm, Postman, and later in the series MongoDB. But for now and this post we just need to have the first two installed.

Let's make sure Python is installed, so load up your favorite command line tool and type the following:

python --version
Enter fullscreen mode Exit fullscreen mode

You should get an output that looks like the following:
Pyhton version in the command prompt

If you have any other message or an error head over to https://www.python.org/downloads/ and download and install. Run the command again and we are good to go.

That's the first part taken care of and now onto the IDE, and IDE stands for an integrated development environment. Now there is Visual Studio Code which is free to download and enjoy and if you feel more comfortable with installing pip packages and setting up virtual environments then please go ahead and use that. For me, PyCharm simply makes this whole process easier. We will have fun with PyCharm in this series and enjoy the Python rich environment it offers! So head over to https://www.jetbrains.com/pycharm/download/#section=windows and grab the link and get downloading.

And last but certainly not least lets grab Postman! https://www.postman.com/downloads/

Now we have everything ready let's start up PyCharm and get a simple endpoint created and some data flowing.

When you first start PyCharm it will offer you the choice to open an existing project or start a new one, so let's go with a brand new one and the next screen is the important one. Here we are going to set up a new virtual environment, for those new to Python like me a virtual environment is a Python environment that the Python interpreter, libraries, and scripts are installed into, they are also isolated from those installed in other virtual environments. So we want to accept the new virtual environment and click create, this will choose the newly installed python as our interpreter and create a brand new project which we can start and debug in real-time - But more on that later!
PyCharm new project

Now we have a new main.py file we should start by deleting everything in it and start from a blank file. So with no text in that file let's install flask.

If you press ctrl+alt+s you will open PyCharm's settings. Inside there click the arrow next to Project:ProjectName and inside there you will see Python Interpreter, click on that and you will be shown all the packages installed with this project. So if you click the plus button you will be greeted with a list and search box, type flask, and press install package. When that's finished close the settings box and we are ready to code.
PyCharm Settings
Install flask

So let's code! The first thing we need to do is tell Python to use Flask, so at the top of our main.py we need to add the following line

from flask import Flask, jsonify
Enter fullscreen mode Exit fullscreen mode

All we are doing here is telling Python to grab flask to use all its features and Jsonify which allows us to create JSON objects. So with that all present we simply need to create a new instance of flask

app = Flask(__name_) 
Enter fullscreen mode Exit fullscreen mode

Now we have a new instance of flask we can call whenever we want
to use it and that is exactly what we are going to do now. If we pop the famous hello world code in below we will be able to see if we get a return in Postman.

@app.route('/', methods=['GET'])
def hello_world():
    return jsonify(message='hello world')
Enter fullscreen mode Exit fullscreen mode

So what is going on? Well, the first line defines our route and in this instance, it's just the main route of our API, then we define the function and return a JSON object with a string message of Hello World. But we need one more thing, and that's for Python to run everything when we spin up our virtual environment.

At the bottom of the main.py file add the following code and this code will simply run our app as soon as we press that magic run button.

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    app.run()
Enter fullscreen mode Exit fullscreen mode

And that is that, Flask is all installed, we have created a new route and we are ready to test in Postman. Our final file code should look like the following:

from flask import Flask, jsonify, request

app = Flask(__name__)


@app.route('/', methods=['GET'])
def hello_world():
    return jsonify(message='hello world')


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    app.run()
Enter fullscreen mode Exit fullscreen mode

At the top of PyCharm you will see a green play button, if you press that it will spin up our venv (Virtual Environment) This will allow us to connect to our API. Once that's done a new terminal box will open and you will be greeted by an IP address that we can use in Postman.
PyCharm Running venv
If we copy the IP address, load Postman we can get started. Postman allows us to make requests to our venv via that IP address, and use different restful methods. To learn more about restful api methods read https://restfulapi.net/. So click the plus button, make sure the dropdown states GET, and paste our IP address into the box.
Postman all running
If we click send we should now receive our message back in the response box and HELLO WORLD!!! We have flask completely set up and running as we should! Good Job!!!

In the next part of this series, we will connect to a DB and start creating the article's endpoint.

Thanks for reading and please subscribe!

Buy me a coffee or pizza

First published: https://www.leighton.com/blog/create-a-flask-api-part-one

Top comments (0)