Flask Part 2: Building a Flask endpoint

August 21, 2016
flask
ios

Creating a Super Simple Flask Endpoint

Post Contents

1. Overview
2. Creating the Super Simple Flask Endpoint
3. Debugging with Postman

1. Overview

In Flask n’ iOS Part 1 we set up just the infrastructure for our endpoint, but we didn’t actually write much logic in our endpoint. Therefore, it might be difficult to follow up that tutorial to do anything useful. In this tutorial, we’re gonna be talking about data. Ultimately, a web application that acts as a server for a mobile application is handling data and most of the tasks related to that data. Tasks is a vague term which could mean handling a search query or storing data. In this post, we’ll focus on the storage aspect of data, because most apps require some aspect of CRUD, (create, read, update, delete).

2. Creating the Super Simple Flask Endpoint

In Flask n’ iOS Part 1 we got to this point in our codebase:

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route("/")
def hello():
	return "<h1 style='color:blue'>Hello There!</h1>"

if __name__ == "__main__":
	app.run(host='0.0.0.0',debug=True)

Let’s just practice editing and restarting our server with a tiny change. Change ‘Hello There!’ to be ‘Hello World’. If you look at your server on the ‘/’ route, you’ll see that your change to the myproject.py file did not update what was being served. In order to update gunicorn and nginx, we have to restart them like so,

sudo systemctl restart myproject
sudo systemctl restart nginx

Now if you view the ‘/’ route again, it should have updated the html text to be ‘Hello World’. Onward!

Our next post will focus on providing simple data persistence on the server, so that you can see how to store some data on your server. To do this, first we’ll add the following route to our myproject.py file.

data = {'links':[]}

@app.route('/data', methods=['POST', 'GET'])
def names():
	
	if request.method == 'GET':
		return jsonify(data)

	if request.method == 'POST':
		content = request.get_json()
		if content is not None:
			link = content['link']
			data['links'].append(link)
			return jsonify(data)

(note remember to import ‘request’ module from flask)

If you restart your server and access the ‘/data’ route, you get a plain text json response with a JSON object that has an array called ‘links’ inside of it.

This route implements a bit more flask logic, and a bit of regular python logic. The regular python logic just creates a dictionary named data with a links array. Then inside our route we modify data based on what requests we receive to our /data route. The flask logic is related to the extra parameter we provided to @app.route() method. For this route, we added the parameter methods=['POST', 'GET']. This tells flask that this route can handle both HTTP POST and GET requests. If you’re not familiar with hypertext transfer protocol (HTTP) then I highly recommend googling it for a bit after this workshop to help get some context. The final bit of logic is our use of the request module. This module is provided via flask and is instantiated with the info from the request flask is currently handling. Therefore, request.method will tell you what type of HTTP request you’re handling. You’ll find this kind of module in many other web frameworks, because handling requests is an important functionality.

3. Debugging with Postman

Postman

This exercise is kinda useless if you don’t know how to send a POST request to your server, so let’s do that now. First, go find an app called ‘postman’ on the interwebz (either standalone or chrome extension). Once you have postman running, click on the + tab to create a new template for an HTTP request. In the dropdown beside the URL input form, change GET to be POST. Now, in the URL form, enter in <server or ip>/data. Now, under the URL form, there should be a tab called Headers. You’ll want to create a header with a key Content-Type and a value application/json. Now, again, under the URL form, there should be a tab called body. Go to that tab, and then select the radiobutton named raw. Finally, enter in {"link":"world"} as the body of the POST request. Hit send a bunch of times with your server running, and the response to your POST requests should be an ever expanding links array. Also, the reason why we needed the application/json header was to inform our server of the type of HTTP request our client was making. Again, this is just a part of the hypertext transfer protocol, which you should have googled by now (YOLO).

Noice! Now you know how to run logic based on the type of network traffic you’re receiving from a client, and more importantly, you know how to debug your server with postman. However, there’s still a problem. What happens when we shut down the server? Find out next time on Flask n’ iOS Part 3!