ga('set', 'anonymizeIp', 1);
Categories: CodingPython

[python] Flask Create RESTful API

Share

This article gives a brief introduction of creating RESTful API using python flask library.

python package

from flask import Flask, render_template, jsonify, request, url_for, redirect, make_response

Flask useful s:

  • Flask
  • render_template
  • jsonify
  • request
  • url_for
  • redirect
  • make_response

Refer the flask API document.

Run flask server

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

@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



  
    Login

In order to get the relative files, we also need to configure CORS setting.

server.py

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

@app.route('/getData', methods=['GET'])
def getData():
    result = {"result": 0,"data":""}
    result["result"] = 1
    result["data"] = "test"
    return jsonify(result)

POST

@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'))
Jys

Published by
Jys

Recent Posts

[Javascript] 新增/刪除JSON中key值

在web訊息交換常會需要對JS... Read More

3 年 前發表

[JAVA] SQL Server Connection

本文介紹JAVA連線SQL s... Read More

3 年 前發表

[python] 檔案整理 – 整理影片檔長度資訊存入excel

本文介紹如何使用python寫... Read More

4 年 前發表