This is the first tutorial of a short series where we will build our own API. In the first part, we will introduce Flask framework, which will be used for our API. It is very easy to install Flask, you just run pip install flask and pip install flask-restful in your terminal. We will also create the first Flask application and connect it with a simple web page.
 

FIRST APPLICATION

Let's start with the creation of the home directory for our API.

In terminal you go to the folder you want to have your application in and run:

> mkdir MyFirstAPI
> cd MyFirstAPI

Now, let's create our first Flask application in directory MyFirstAPI. In this tutorial, we will call it my_first_api.py. The source code of the application is below.

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__, static_url_path='')
api = Api(app)

@app.route("/", methods=['POST', 'GET'])
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000')


Now we can check step by step what exactly our code does.

  • Firstly, we import the Flask class. An instance of this class is our application.
  • Next, we create an instance of this class. The argument is the name of the application’s module or package. If you are using a single module (as in this example), you should use __name__. This affects where the flask application looks for templates and static files.
  • The route() decorator is used to tell Flask what URL should trigger our function. In our example, we trigger function on "/" therefore directly after accessing URL of the application: 0.0.0.0:5000
  • We can give the function any name we want and we specify the message we want to display in the user’s browser, in our case "Hello, World!".

You need to execute the script from the terminal to start the application.

> python my_first_api.py

Now go to the URL 0.0.0.0:5000 to see if the server runs.
 

ADDING HTML FILES

We have successfully launched our first Flask server, where our API will run. As the next step, we will make an application to communicate with web pages (HTML files). For this, we need to import the render_template method.

from flask import render_template

This method will look for HTML files in the specified directory and show them on our server. Let's go back to the terminal to create a sub directory for our templates.

> mkdir templates

Run the command above in your home directory of the application to create the sub directory templates. Since we use default settings in our application, we have to name the sub directory exactly "templates" so Flask is able to find it. Afterward, we create two HTML files: index.html and results.html and insert the following code into file index.html. Keep the file results.html empty for now.

<!DOCTYPE html>
<html lang="en">
<HEAD>
        <TITLE>
            My First API
        </TITLE>      
</HEAD>
<BODY>  
    <p> Hello, world!! </p>
</BODY>
</html>

The first line informs the browser that the file should be rendered as HTML document. The full code of the web page is inside the <html> tag and the page has two parts - <head> and <body>. In the head part, we will specify the title of the web page. Furthermore, if your web page is more complicated, you can load javascript and CSS libraries in this part. The actual body and content of the page are in the part <body>. For now, we will put there just one paragraph with "Hello, world!!"

When we have our file index.html ready, we will adapt the function hello_world().

@app.route("/index.html", methods=['POST', 'GET'])
def hello_world():
    return render_template("index.html")

Now the application triggers the function hello_world() on a different URL. Remember this when you go to your browser to check if the application works. The function render_template() which we imported from module Flask will locate the HTML file and send it to a browser for rendering. You need to make sure that your file is in the sub directory templates. Otherwise, Flask will not find it. 

After restarting your server, you can go to the URL 0.0.0.0:5000/index.html and you will see the text "Hello, world!!" The result is the same as before but we have told Flask to use our own web page.


CONCLUSION

We hope that after this tutorial you will be able to create your own Flask application and to use your own HTML files with it. Next week we will show you how to add some useful functions into the application. In the meantime, you can check our online bootcamp online.basecamp.com for more Data Science education.

 

Comment