API介面測試--python實現請求
阿新 • • 發佈:2021-08-05
前面章節講解到工具postman測試介面,傳送請求;本節講解如何使用python語言傳送請求。
一、python傳送get請求
安裝requests庫,pip install request
傳送get請求,使用requests裡面的get方法。以查詢天氣為例
url = "http://apis.juhe.cn/simpleWeather/query" data = { "key":"c904a499ae9bcda8d4c8383d0c516fa1", "city":"深圳" } header={ "content-type":"application/json" } r = requests.get(url,params=data,headers =header) print(r.text)
get的第一個引數為url,即請求的介面地址;第二個引數為請求資料,如果沒有請求資料可以不寫,同理headers也是,這個是請求頭部,沒有也可以不寫。
r.text是返回響應的內容,如果需要返回狀態碼 ,使用 r.status_code
二、python傳送post請求
使用python傳送post請求,可以使用requests裡面的post方法.
1.提交的資料型別為:application/json
import json import requests url = "http://localhost:8088/login" headers = { "content-type":"application/json" } data = { "user":"admin", "password":"123456" } r = requests.post(url,headers=headers,json=data) #或者 r = requests.post(url,headers=headers,data=json.dumps(data))
2.提交的資料型別為application/x-www-form-urlencoded
import requests url = "http://localhost:8088/login" headers = { "content-type":"application/x-www-form-urlencoded" } data = { "user":"admin", "password":"123456" } r = requests.post(url,headers=headers,data=data)
3.提交的資料型別為multipart/form-data
此資料型別一般用於檔案的上傳
import requests url = "http://localhost:8088/post" files = {'file': open('/home/test.jpg', 'rb')} r = requests.post(url,headers=headers,files=files)