我们可以通过start.spring.io网站轻松地用spring引导REST应用程序,任何人都知道有什么好的网站可以让我用python获得REST项目的骨架吗?我的目的是使用python开发REST应用程序。
发布于 2021-12-28 20:20:09
这样做的方法之一是使用Python中的请求模块。使用以下命令将其导入到代码中:
导入请求
现在,每个API都是不同的,因此您必须与供应商一起了解需求是什么。为了测试和学习目的,我建议使用httpbin (https://httpbin.org)。你几乎可以在那里测试任何东西。
以下是几个简单的请求:
#returning status
url = 'https://httpbin.org/post'
response = requests.post(url)
print(response.status_code)
print(response.ok)
#sending data/getting text response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.text)
#sending data/getting json response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.json())
#sending time data to server
import datetime
url = 'https://httpbin.org/post'
params = {'Time':f'{datetime.datetime.now()}'}
response = requests.post(url, params=params)
print(response.text)
#Params vs Data
#params
url = 'https://httpbin.org/post'
params = {'username':'jsmith','password':'abc123'}
response = requests.post(url, params=params)
print(response.text)
#data
url = 'https://httpbin.org/post'
payload = {'username':'jsmith','password':'abc123'}
response = requests.post(url, data=payload)
print(response.text)
# ********* HEADERS **********
url = 'https://httpbin.org/get'
response = requests.get(url)
print(response.text)
url = 'https://httpbin.org/post'
headers = {'content-type': 'multipart/form-data'}
response = requests.post(url,headers=headers)
print(response.request.headers) #client request headers
print(response.headers) #server response headers
print(response.headers['content-type']) #request header value from server要使用实际的API,我建议使用RapidAPI (https://rapidapi.com/),它是一个可以连接到数千个API的中心。HEre是一个使用的示例代码:
#RapidAPI
#Google Translate
import requests
url = "https://google-translate1.p.rapidapi.com/language/translate/v2"
text = 'Ciao mondo!'
to_lang = 'en'
from_lang = 'it'
payload = f"q={text}&target={to_lang}&source={from_lang}"
headers = {
'content-type': "application/x-www-form-urlencoded",
'accept-encoding': "application/gzip",
'x-rapidapi-host': "google-translate1.p.rapidapi.com",
'x-rapidapi-key': "your-API-key"
}
response = requests.post(url, data=payload, headers=headers)
print(response.json()['data']['translations'][0]['translatedText'])https://stackoverflow.com/questions/70512006
复制相似问题