Flask Tutorial # 2 ~ POST, PUT, DELETE Request ~

What to do this time

Last time, we mainly implemented the processing for GET requests (Tutorial # 1). This time, I will write the processing for POST request, PUT request, and DELETE request in Flask. In addition, DB linkage will be introduced in the next article, so this time I would like to make changes to the array defined in the global variable.

For details, see here.

POST request

First, I will write the processing for the POST request. POST is mainly used to add data. This time the requester will use the curl command to simplify the test.

$ curl -X POST -H "Content-Type: application/json" -d '{"title":"New post", "body":"New postです"}' localhost:5000/post/add

-X specifies the request method, -H specifies the request header, and -d specifies the request body. This is a statement that means to send a POST request to localhost: 5000 / post / add in json format.

The flask side looks like this

app.py


@app.route('/post/add', methods=['POST'])
def create_post():
    post = request.json
    db_data.append(post)
    return jsonify(db_data)

The body requested in json format can be received in request.json. Append the received articles to an array to complete the article addition process. This time, as a test, the article list (db_data) changed in all response processing is returned.

PUT request

Next, we will write the processing for the PUT request. This is mainly used to modify the data.

terminal


$ curl -X PUT -H "Content-Type: application/json" -d '{"title":"Post correction", "body":"This is a fixed post"}' localhost:5000/post/update/0

The statement means to send a PUT request to localhost: 5000 / post / update / 0. Here, the array index is specified as the article id after / update.

The code on the flask side looks like this

app.py


@app.route('/post/update/<id>', methods=['PUT'])
def update_post(id):
    post = request.json
    db_data[int(id)] = post
    return jsonify(db_data)

In flask, you can pass parameters to a function by specifying / <parameter> for route. The idth article in the array is replaced with the article content received from the request.

DELETE request

Finally, the processing for the DELETE request. This is mainly used when deleting data.

terminal


$ curl -X DELETE localhost:5000/post/delete/1

At the end of the update, we are passing the index of the array of articles that we want to delete as a parameter.

Flask looks like this.

app.py


@app.route('/post/delete/<id>', methods=['DELETE'])
def delete_post(id):
    db_data.pop(int(id))
    return jsonify(db_data)

It's almost the same as when updating.

Summary

How was that? This time, Flask implemented processing for POST, PUT, and DELETE requests. In # 3, I would like to continue DB linkage with the route as it is.

Recommended Posts

Flask Tutorial # 2 ~ POST, PUT, DELETE Request ~
Flask Tutorial # 1 ~ GET Request ~
Flask Tutorial # 3 ~ DB Linkage ~