This article gives a brief introduction of creating RESTful API using python flask library.
python package
1 |
from flask import Flask, render_template, jsonify, request, url_for, redirect, make_response |
Flask useful functions:
- Flask
- render_template
- jsonify
- request
- url_for
- redirect
- make_response
Refer the flask API document.
Run flask server
1 2 3 |
app = Flask(__name__) if __name__ == '__main__': app.run(host="0.0.0.0", port="5000", debug=True) |
Configure the ip and port then launch the flask server.
Route
Return html
1 2 3 |
@app.route('/') def index(): return render_template('index.html') |
html with flask
Below is the html code if you want to get the relative filepath such as the css files and the js files.
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html> <head> <link rel="shortcut icon" href="#"/> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="{{url_for('static', filename='css/myCss.css')}}"/> <link rel="stylesheet" href="{{url_for('static', filename='css/bootstrap.min.css')}}"/> <title>Login</title> </head> <body> <script src="{{url_for('static', filename='js/jquery3.6.0.js')}}"></script> <script src="{{url_for('static', filename='js/bootstrap.min.js')}}"></script> </body> </html> |
In order to get the relative files, we also need to configure CORS setting.
server.py
1 2 3 4 5 6 7 8 9 10 11 |
from flask import Flask, render_template, jsonify, request, url_for, redirect, make_response from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': app.run(host="0.0.0.0", port="5000", debug=True) |
Startup the flask server by command line:python server.py
RESTful API return JSON
GET
1 2 3 4 5 6 |
@app.route('/getData', methods=['GET']) def getData(): result = {"result": 0,"data":""} result["result"] = 1 result["data"] = "test" return jsonify(result) |
POST
1 2 3 4 5 6 7 8 |
@app.route('/postData', methods=['POST']) def postData(): # if POST data is json format VAL_FROM_JSON = request.json.get('KEY') # if POST data resource is form submit VAL_FROM_FORM = request.form.get('KEY') # if return page is index route return redirect(url_for('index')) |
留言