Practical Python API Interface Writing

1, Operation steps

  1. Import: import flag, JSON
  2. Instantiation: API= Flask Flask( Name
  3. Define interface access path and access method: @API. route ('/index', methods= ['get/post/PUT/Delete '])
  4. Define the function, ensuring that it matches the name of the path, set the return type, and support Chinese: def index(): return json. dumps (ren, ensure.ascii= False)
  5. Three types of input parameter access interfaces:
    5.1 URL format input: flask. request. args. get ('id ')
    5.2 Form data format input: pwd= Flask. request. values. get ('pwd ')
    5.3 Josn format input parameter: pwd= Flask. request. json. get ('pwd ')
  6. Start service: api-run (port= 8888, debug= True, host= '127.0.0.1'). After starting the service, you can use ip+ Port; Path; Enter parameter access interface

2, Source code examples

#!/usr/bin/python3
# encoding:utf-8
import flask,json
#instantiation api take the current one python treating files as a service, __name__represents the current one python file 
api = flask.Flask(__name__) 

# 'index'it is the interface path, methods do not write, default get request 
@api.route('/index',methods=['get']) 
# get method access 
def index():
ren = {'msg':'successfully accessed the homepage','msg_code':200}
#json.dumps when serializing, the default usage for chinese is ascii coding . to output chinese, you need to specify ensure_ascii=False
return json.dumps(ren,ensure_ascii=False)

#post accessing method 1 :url format parameters 
@api.route('/article',methods=['post']) 
def article():
#url format parameters? id=12589&name='lishi'
id = flask.request.args.get('id')

if id:
if id == '12589':
ren = {'msg':'successfully accessed article','msg_code':200}
else:
ren = {'msg':'unable to find article','msg_code':400}
else:
ren = {'msg':'please enter the article id parameter','msg_code':-1}
return json.dumps(ren,ensure_ascii=False)

#post accessing method 2 :from-data(k-v )format parameters 
@api.route('/login',methods=['post'])
def login():
#from-data format parameters 
usrname = flask.request.values.get('usrname')
pwd = flask.request.values.get('pwd')

if usrname and pwd:
if usrname =='test' and pwd =='123456':
ren = {'msg':'login successful','msg_code':200}
else:
ren = {'msg':'incorrect username or password','msg_code':-1}
else:
ren = {'msg':'user name or password is empty','msg_code':1001}
return json.dumps(ren,ensure_ascii=False)

#post accessing method 2 :josn format parameters 
@api.route('/loginjosn',methods=['post'])
def loginjosn():
#from-data format parameters 
usrname = flask.request.json.get('usrname')
pwd = flask.request.json.get('pwd')

if usrname and pwd:
if usrname =='test' and pwd =='123456':
ren = {'msg':'login successful','msg_code':200}
else:
ren = {'msg':'incorrect username or password','msg_code':-1}
else:
ren = {'msg':'user name or password is empty','msg_code':1001}
return json.dumps(ren,ensure_ascii=False)

if __name__== '__main__':
api.run(port=8888,debug=True,host='127.0.0.1') #start service 
# debug=True after changing the code, there is no need to restart, it will automatically restart 
# 'host='127.0.0.1'other IP access address 

Running results:

 * Serving Flask app 'monitor' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 991-833-116
* Running on http://127.0.0.1:8888/ (Press CTRL+C to quit)
127.0.0.1 - - [16/Jan/2022 14:05:53] "POST /login?usrname=test&pwd=123456 HTTP/1.1" 200 -
127.0.0.1 - - [16/Jan/2022 14:08:34] "GET /index HTTP/1.1" 200 -

Request method:
Is it feasible to use Postman to test the interface For example:
URL: 127.0.1:1:8888/login
Parameter: usrname= Test; Pwd= one hundred and twenty-three thousand four hundred and fifty-six.

Several methods to obtain request parameters:

flask.request.form.get("key", type=str, default=None )get form data, 
flask.request.args.get("key")get get request parameters, 
flask.request.values.get("key")get all parameters. 

Related articles