[PYTHON] Flask Tutorial # 1 ~ GET Request ~

What is Flask

Flask is a Python web application framework It works the same as Django. However, it differs from Django in that it's called a micro-framework and is implemented at a minimum. Maybe some people couldn't keep up with the Django tutorials because they suddenly came up with a lot of elements such as database connections, templates and views.

Implementation goal

This time, we will build an API server that returns a JSON-formatted response without using views or templates. The article here is the final goal

Here introduces in detail

Preparation

Install flask.

pip install flask

Only this. Easy!

HelloWorld

Let's start with hello world. Make app.py

app.py


from flask import Flask

app = Flask(__name__)

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

Create an instance of your app and define a route. Under the route definition, write the processing when a request comes to the specified URL. This is a statement that means that hello world will be returned when a GET request comes to the root.

app.py


if __name__ == '__main__':
    app.debug = True
    app.run()

Write the main process below the previous sentence. By setting debug mode to True, it will restart automatically when the program is rewritten. If you can do this

terminal


python app.py

It is executed by. If you access localhost: 5000 with your browser, hello world will appear.

GET request

Next, we will write the processing for the GET request. This is mainly used for data acquisition. This time we will assume a blog application. Since DB connection is done in # 3, here we define the article list in the global variable. The content of the article is simply title and body. Let's implement it.

app.py


from flask import Flask, jsonify, request # <= jsonify,request added

db_data = [
    {'title': 'Title 1', 'body': 'Body 1'},
    {'title': 'Title 2', 'body': 'Body 2'},
    {'title': 'Title 3', 'body': 'Body 3'},
    {'title': 'Title 4', 'body': 'Body 4'},
    {'title': 'Title 5', 'body': 'Body 5'},
]

app.config['JSON_AS_ASCII'] = False 

@app.route('/posts', methods=['GET'])
def get_all_posts():
    limit = request.args['limit']
    return jsonify(db_data[:int(limit)])

This is a statement that means to get all articles when a GET request comes to / posts. If you pass the query to the URL, you can get the value of the corresponding query with request.args ['query name']. This time, specify the number of articles to be acquired by limit. I want the response format to be json format, so I use a function called jsonify.

Now that it's complete, let's check it with a browser. If you try to access it with localhost: 5000 / posts? Limit = 3, you should see 3 articles.

Parameter specification

Next, we will get individual articles by specifying the ID. The flask code looks like this.

app.py


@app.route('/post/<id>', methods=['GET'])
def get_post(id):
    return jsonify(db_data[int(id)])

In flask, you can specify parameters in the URL with / <parameter name>. The specified parameter can be received by the function. This time, DB uses an array instead, so specify the index of the array.

If you access it with a browser at localhost: 5000 / post / 0, you can get the 0th article.

Summary

How was that? This time I mainly tried processing GET requests with Flask. # 2 implements processing for POST, PUT, and DELETE requests.

Recommended Posts

Flask Tutorial # 1 ~ GET Request ~
Flask Tutorial # 2 ~ POST, PUT, DELETE Request ~
Flask Tutorial # 3 ~ DB Linkage ~
About Go GET request
Get started with Django! ~ Tutorial ⑤ ~
Get query parameters for Flask GET
Get started with Django! ~ Tutorial ④ ~
Get started with Django! ~ Tutorial ⑥ ~
flask
flask
Get a Boolean in Flask's request
Get data from Cloudant with Bluemix flask
Flask tutorial (from installation to hello world)
(For myself) Flask_3 (form, POST and GET)