【问题标题】:How to create a simple REST api WEB application with Python如何使用 Python 创建一个简单的 REST api WEB 应用程序
【发布时间】:2022-01-27 09:27:18
【问题描述】:

我们可以通过 start.spring.io 网站轻松地使用 spring boot 制作 REST api 应用程序,有人知道有什么好的网站可以通过它使用 python 获取骨架 REST api 项目吗?我的目的是用python制作REST api应用程序。

【问题讨论】:

  • 要求我们推荐或查找书籍、工具、软件库、教程或其他非现场资源的问题对于 Stack Overflow 来说是题外话,因为它们往往会吸引固执己见答案和垃圾邮件。相反,describe the problem 以及迄今为止为解决它所做的工作。
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python api rest


【解决方案1】:

其中一种方法是使用 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 的中心。这是使用谷歌翻译的示例代码:

#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'])

【讨论】:

    猜你喜欢
    • 2011-06-12
    • 2016-12-16
    • 2014-05-31
    • 2018-09-13
    • 1970-01-01
    • 2015-03-31
    • 2021-05-22
    • 2017-04-07
    • 2016-06-04
    相关资源
    最近更新 更多