DEV Community

Timothy Kenno Handojo
Timothy Kenno Handojo

Posted on

Building a RESTful API with Flask - part 0: getting started

There can be some mystique aura surrounding APIs, and REST API is no exception. When I first got started with my current job position, I had no idea what the heck it was, yet had build one myself (with my team, of course). With this article, I hope to demistify this mystery and show that you can build one too!

For the technology stack, we'll have Python 3.7 or above. We'll be building our stuff on top of Flask micro-framework. To test, we'll be using cURL (Windows users, you should have it by now). We'll also need a Linux box running as a production server. There's actually quite a bit more to that, but we'll get to that. As for now, this should be enough.

Let's get started!

Setting up the environment

If you haven't made a directory for your project, do it now. If you've never done it before, better start doing so now!

For this example, I'll be naming my directory restful-api. Let's point our terminal to that and run python3 -m venv venv to install the virtual environment. Windows user would wanna run py -3 -m venv venv instead. You will now see a new directory called venv.

With this virtual environment, you get to install any python packages without touching any of your actual system files. When you're done with it (or somehow mess it up), you can just delete it and create new one when you're ready to use it again. Avoid the temptation to move it around as it won't work (I've learned it the hard way).

Before you do anything, the virtual environment needs to be activated. Unlike what you did above, this one needs to be done everytime you open a new terminal to run anything (e.g. when you're getting back from a break). To do so, run . venv/bin/activate. Windows user would instead run venv\Scripts\activate.

Now, assuming you're already in the virtual environment, you will install the necessary python packages. Run pip install flask. Windows user would do the same.

Creating the App

After the installation finish (or while waiting for it), create a new directory called app where you will do most of your work. Create a file called __init__.py and fill it with:

from flask import Flask

def create_app(config_object=None):
    app = Flask(__name__)

    @app.route('/')
    def hello():
        return 'Hello World!\n'

    return app
Enter fullscreen mode Exit fullscreen mode

That's it! You've created a working application.

Check out the Flask documentation for more information on how it works.

You actually could've put everything in a single file and make everything much simpler like in many other tutorials. However, this method would make it more manageable when scaling bigger. You can thank me later.

Testing the App

To test it (after the installation finish), run flask run. You can see it in your terminal that the app is now accessible thru http://127.0.0.1:5000.

To access this, you can use any HTTP client. Web browser would do for this step (go on, try it!), but not for the next ones as we'd need to manipulate our request data with relative ease.

So we'll use cURL, a command line HTTP client. Now open a new terminal and type curl http://127.0.0.1:5000 (alternatively, can type curl localhost:5000).

You may have been using Postman. If you're already familiar with it, you can use it to test this app.

kenno-ideapad:[kenno]:~$ curl localhost:5000
Hello World!kenno-ideapad:[kenno]:~$ curl http://127.0.0.1:5000/
Hello World!kenno-ideapad:[kenno]:~$ 
Enter fullscreen mode Exit fullscreen mode

Touching up

But wait, shouldn't RESTful API be doing stuff in JSON?

That is true... and I was just showing you how to get things working.

Now to get it working in JSON, we're going to revisit app/__init__.py.

Go to the line with from flask import Flask and add , jsonify at the end, turning it into from flask import Flask, jsonify

Now go to the function hello() and change its return statement from return 'Hello World!\n' to return jsonify({'message': 'Hello World!'}).

You will now have on your app/__init__.py

from flask import Flask, jsonify

def create_app(config_object=None):
    app = Flask(__name__)

    @app.route('/')
    def hello():
        return jsonify({'message': 'Hello World!'})

    return app
Enter fullscreen mode Exit fullscreen mode

Restart the application by pressing Ctrl-C on the console and running flask run again.

Check again with your cURL.

kenno-ideapad:[kenno]:~$ curl http://127.0.0.1:5000/
{"message":"Hello World!"}
kenno-ideapad:[kenno]:~$ curl localhost:5000
{"message":"Hello World!"}
kenno-ideapad:[kenno]:~$ 
Enter fullscreen mode Exit fullscreen mode

Better?

Stay tuned for the next part! While at it, get your Linux box ready and get it on your home network.

Top comments (0)