利用python寫api接口實戰指南

一、操作步驟

  1. 導入:import flask,json
  2. 實例化:api = flask.Flask(name)
  3. 定義接口訪問路徑及訪問方式:@api.route(’/index’,methods=[‘get/post/PUT/DELETE’])
  4. 定義函數,註意需與路徑的名稱一致,設置返回類型並支持中文:def index(): return json.dumps(ren,ensure_ascii=False)
  5. 三種格式入參訪問接口:
    5.1 url格式入參:flask.request.args.get(‘id’)
    5.2 form-data格式入參:pwd = flask.request.values.get(‘pwd’)
    5.3 josn格式入參:pwd = flask.request.json.get(‘pwd’)
  6. 啟動服務:api.run(port=8888,debug=True,host=‘127.0.0.1’),開啟服務之後,就可以通過ip+端口+路徑+入參訪問接口

二、源碼舉例

#!/usr/bin/python3
# encoding:utf-8
import flask,json
# 實例化api,把當前這個python文件當作一個服務,__name__代表當前這個python文件
api = flask.Flask(__name__) 
 
# 'index'是接口路徑,methods不寫,默認get請求     
@api.route('/index',methods=['get']) 
# get方式訪問
def index():
  ren = {'msg':'成功訪問首頁','msg_code':200}
  #json.dumps 序列化時對中文默認使用的ascii編碼.想輸出中文需要指定ensure_ascii=False
  return json.dumps(ren,ensure_ascii=False)
 
#post入參訪問方式一:url格式參數
@api.route('/article',methods=['post']) 
def article():
  #url格式參數?id=12589&name='lishi'
  id = flask.request.args.get('id')
   
  if id:
    if id == '12589':
      ren = {'msg':'成功訪問文章','msg_code':200}
    else:
      ren = {'msg':'找不到文章','msg_code':400}
  else:
    ren = {'msg':'請輸入文章id參數','msg_code':-1}
  return json.dumps(ren,ensure_ascii=False)
 
#post入參訪問方式二:from-data(k-v)格式參數
@api.route('/login',methods=['post'])
def login():
  #from-data格式參數
  usrname = flask.request.values.get('usrname')
  pwd = flask.request.values.get('pwd')
   
  if usrname and pwd:
    if usrname =='test' and pwd =='123456':
      ren = {'msg':'登錄成功','msg_code':200}
    else:
      ren = {'msg':'用戶名或密碼錯誤','msg_code':-1}
  else:
    ren = {'msg':'用戶名或密碼為空','msg_code':1001}
  return json.dumps(ren,ensure_ascii=False)
 
#post入參訪問方式二:josn格式參數  
@api.route('/loginjosn',methods=['post'])
def loginjosn():
  #from-data格式參數
  usrname = flask.request.json.get('usrname')
  pwd = flask.request.json.get('pwd')
   
  if usrname and pwd:
    if usrname =='test' and pwd =='123456':
      ren = {'msg':'登錄成功','msg_code':200}
    else:
      ren = {'msg':'用戶名或密碼錯誤','msg_code':-1}
  else:
    ren = {'msg':'用戶名或密碼為空','msg_code':1001}
  return json.dumps(ren,ensure_ascii=False)
 
if __name__ == '__main__':
  api.run(port=8888,debug=True,host='127.0.0.1') # 啟動服務
  # debug=True,改瞭代碼後,不用重啟,它會自動重啟
  # 'host='127.0.0.1'別IP訪問地址

運行結果:

 * 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 –

請求方式:

使用postman測試接口是否可行

如:

url:127.0.0.1:8888/login

參數:usrname=test;pwd=123456

獲取請求參數的幾種方法:

flask.request.form.get("key", type=str, default=None) 獲取表單數據,
flask.request.args.get("key") 獲取get請求參數,
flask.request.values.get("key") 獲取所有參數。

總結

到此這篇關於利用python寫api接口實戰指南的文章就介紹到這瞭,更多相關python寫api接口內容請搜索LevelAH以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持LevelAH!

推薦閱讀: