基于Flask框架编写WebAPI服务
1.webapi
from flask import Flask, jsonify, abort, request
app = Flask(__name__)
app.config.update(RESTIFUL_JSON=dict(ensure_ascii=False))
@app.route("/")
def api_root():
return "welcome"
@app.route('/tg', methods = ["GET"])
def api_test_get():
return "test get"
@app.route('/entities/api/v1/students', methods = ["GET"])
def get_students():
return jsonify({"students" : students}), 200
@app.route('/entities/api/v1/student/<int:id>', methods = ["GET"])
def get_student(id):
for key in students:
if key == id:
return jsonify({"students" : students[key]})
return jsonify({"error" : "not found student"}), 400
@app.route('/entities/api/v1/student/<int:id>',methods = ["POST"])
def add_student(id):
print("get post id : ", id)
print(request.form)
if not request.form:
abort(400)
# dict_form = json.
if id in students:
abort(409)
student = {"name" : request.form['name'],
"age" : request.form['age'],
"sex" : request.form['sex']}
students[id] = student
return jsonify({"message" : "add student ok"}), 200
@app.route('/entities/api/v1/student<int:id>', methods = ["PUT"])
def update_student(id):
for key, student in students.items():
if key == id:
student['name'] = request.form['name']
student['age'] = request.form['age']
student['sex'] = request.form['sex']
return jsonify({"message" : "alter student ok"})
abort(400)
@app.route('/entities/api/v1/student/<int:id>', methods = ['DELETE'])
def delete_student(id):
if id in students:
students.pop(id)
return jsonify({"message" : "delete ok"}), 200
else:
abort(400)
if __name__ == '__main__':
print("ok")
app.run()
2.请求webapi
2.1 get请求
import requests
url = "http://127.0.0.1:5000/entities/api/v1/students"
result = requests.get(url)
status_code = requests.status_code
response_dict = requests.json()
for key, value in respons_dict["students"].items():
print(key, value)
2.2 post请求
url = "http://127.0.0.1:5000/entities/api/v1/student/1006"
r = requests.post(url, {"name" : "hexiao", "age" : "10", "sex" : "女"})
print(r.status_code)
response_dict = r.json()
print(response_dict)
3.常用状态码
Successful 200(OK) 201(Created) 204(No Content) Rediction 304(Not Modified) Client-Side Error 400(Bad Request) 401(Unauthorized) 404(Not Found) 409(Conflict)