
About a week back I had asked some of my juniors to build a flask app. The result was a mixture of classes and Resource implementation of flask_restful library. When asked why they made it so complex, he showed me the google search results for – how to build REST API’s using flask. Almost all the tutorials out there are either too in-depth or too difficult for beginners.This post is a beginner friendly tutorial on how to build flask API’s.
Before we start – a few jargon.
Flask: is a Python-based microframework that enables you to build web applications. The “micro” in microframework means Flask aims to keep the core simple but extensible.
REST: a RESTful API uses HTTP requests to GET, PUT, POST and DELETE data.
RESTful API designing: guidelines is a must read before you continue. It talks about terminologies, endpoints, versioning status codes and so much more.
Routing
Let’s take this program snippet for example –
app = Flask(__name__) | |
@app.route("/") | |
def hello(): | |
return "Hello World!" |
Using @app.route you define which function will run when a particular endpoint(URL) is called. Inside the route decorator you can define the API endpoint, the methods that will activate the function below it.
URL patterns
app = Flask(__name__) | |
@app.route("/hello/<username>") | |
def hello_user(username): | |
return "Hello {} !".format(username) |
In the above example, the <username> can be anything. A variable, that is used as a parameter for the function below the decorator. This is one of the ways using which you can pass variables from your front-end to your backend.
GET request
The following snippet creates an API to recieve 2 numbers and return their sum.
Using URL parameters: eg – http://127.0.0.1:5000/?num1=2&num2=40
from flask import Flask, request | |
app = Flask(__name__) | |
@app.route('/', methods=['GET']) | |
def add(): | |
num1 = request.args.get('num1') | |
num2 = request.args.get('num2') | |
return num1 + num2 | |
if __name__ == "__main__": | |
app.run() |
The same task using form data –
from flask import Flask, request, jsonify | |
app = Flask(__name__) | |
@app.route('/add', methods=['GET']) | |
def add(): | |
data = request.form | |
num1 = int(data["num1"]) | |
num2 = int(data["num2"]) | |
sum = num1 + num2 | |
return str(sum) | |
if __name__ == "__main__": | |
app.run(debug=True) |
And the same using json data –
from flask import Flask, request, jsonify | |
app = Flask(__name__) | |
@app.route('/add', methods=['GET']) | |
def add(): | |
data = request.json | |
num1 = data["num1"] | |
num2 = data["num2"] | |
sum = num1 + num2 | |
return jsonify({"sum": sum}) | |
if __name__ == "__main__": | |
app.run(debug=True) |
You can use the above examples with different types of request types by changing the method’s parameter.
Handling GET and POST request in the same function
from flask import Flask, request | |
app = Flask(__name__) | |
@app.route('/add', methods=['GET','POST']) | |
def add(): | |
if request.method == 'POST': | |
data = request.json | |
num1 = data["num1"] | |
num2 = data["num2"] | |
sum = num1 + num2 | |
return jsonify({"sum": sum}) | |
elif request.method == 'GET': | |
return "Hello World!" | |
if __name__ == "__main__": | |
app.run(debug=True) |