analitics

Pages

Friday, August 2, 2019

Python 3.7.3 : Using the flask - part 006.

Today I will show you how to use the RESTful API application with flask python module that uses HTTP requests to GET, PUT, POST and DELETE data.
When HTTP is used, as is most common, the operations (HTTP methods) available are GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS and TRACE.[2], see the Wikipedia article.
All of these HTTP methods will be tested with postman software.
You need to have an account and use the downloaded software in order to interrogate with these methods.
Let's see the source new code first:
@app.route("/users/", methods=['GET'])
def users():
    users = User.query.all()
    #return users_schema.jsonify(users)
    all_users = users_schema.dump(users)
    return jsonify(all_users.data)

@app.route("/users/", methods=['POST'])
def user_post(id):
    user_post = User.query.get(id)
    print(user_post)
    username = request.json['username']
    email = request.json['email']
    user_post.username = username
    user_post.email = email
    db.session.commit()
    return user_schema.jsonify(user_post)

@app.route("/users/", methods=['PUT'])
def user_put(id):
    user_put = User.query.get(id)
    print(user_put)
    username = request.json['username']
    email = request.json['email']
    user_put.username = username
    user_put.email = email
    db.session.commit()
    return user_schema.jsonify(user_put)

@app.route("/users/", methods=['DELETE'])
def user_delete(id):
    user_delete = User.query.get(id)
    print(user_delete)
    db.session.delete(user_delete)
    db.session.commit()
    return user_schema.jsonify(user_delete)
Using the postman you can test it by running the python script and call these methods at http://127.0.0.1:5000/users/.