首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Python创建简单的REST应用程序

如何使用Python创建简单的REST应用程序
EN

Stack Overflow用户
提问于 2021-12-28 20:05:57
回答 1查看 186关注 0票数 -2

我们可以通过start.spring.io网站轻松地用spring引导REST应用程序,任何人都知道有什么好的网站可以让我用python获得REST项目的骨架吗?我的目的是使用python开发REST应用程序。

EN

回答 1

Stack Overflow用户

发布于 2021-12-28 20:20:09

这样做的方法之一是使用Python中的请求模块。使用以下命令将其导入到代码中:

导入请求

现在,每个API都是不同的,因此您必须与供应商一起了解需求是什么。为了测试和学习目的,我建议使用httpbin (https://httpbin.org)。你几乎可以在那里测试任何东西。

以下是几个简单的请求:

代码语言:javascript
复制
#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是一个使用的示例代码:

代码语言:javascript
复制
#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'])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70512006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档