使用 Python 编写 API(使用 Flask 和 RapidAPI)

使用 Python 编写 API(使用 Flask 和 RapidAPI)

如果您正在阅读本文,您可能已经熟悉使用 API(应用程序编程接口)带来的可能性。

通过将众多开放 API 之一添加到您的应用程序,您可以扩展应用程序的功能或使用必要的数据丰富它。 但是,如果您开发了一项独特的功能并想与社区分享怎么办?

答案很简单:你需要 创建您自己的 API.

尽管乍一看这似乎是一项艰巨的任务,但实际上很简单。 我们将向您展示如何使用 Python 来完成此操作。

您需要什么才能开始

要开发 API,您需要:

  • 蟒蛇3;
  • 长颈瓶 — 用于创建 Web 应用程序的简单易用的框架;
  • Flask-RESTful 是 Flask 的扩展,允许您以最少的配置快速开发 REST API。

使用以下命令执行安装:

pip install flask-restful

我们为初学者推荐免费的强化编程课程:
使用 C# 开发 Telegram 机器人 — 26 月 28 日至 XNUMX 日。 免费的强化课程,让您了解助理机器人的工作原理、使用 Telegram API 的细节以及其他细微差别。 前三名最佳参赛者将获得技能箱的 30 卢布.

在你开始之前

我们将开发一个具有基本功能的 RESTful API CRUID功能.

为了充分理解该任务,让我们理解上面提到的两个术语。

什么是休息?

REST API(表述性状态传输)是一种使用 HTTP 请求交换数据的 API。

REST API 必须满足某些标准:

  • 客户端-服务器架构:客户端与用户界面交互,服务器与后端和数据存储交互。 客户端和服务器是独立的,任何一个都可以单独替换。
  • 无状态 - 客户端数据不存储在服务器上。 会话状态存储在客户端。
  • 可缓存性——客户端可以缓存服务器响应以提高整体性能。

什么是增删改查?

欺诈 是一个编程概念,描述了四个基本操作(创建、读取、更新和删除)。

在 REST API 中,请求类型和请求方法负责 post、get、put、delete 等操作。

现在我们了解了基本术语,我们可以开始创建 API。

进入菜单

让我们创建一个有关人工智能的引言存储库。 人工智能是当今发展最快的技术之一,而 Python 是一种流行的人工智能工具。

借助此 API,Python 开发人员可以快速获取有关 AI 的信息并从新进展中获得灵感。 如果开发人员对此主题有宝贵的想法,他将能够将它们添加到存储库中。

让我们首先导入必要的模块并设置 Flask:

from flask import Flask
from flask_restful import Api, Resource, reqparse
import random
app = Flask(__name__)
api = Api(app)

在此代码片段中,Flask、Api 和 Resource 是我们需要的类。

Reqparse 是一个 Flask-RESTful 查询解析接口...您还需要一个随机模块来显示随机报价。

现在我们将创建一个有关人工智能的引言存储库。

每个存储库条目将包含:

  • 数字身份证;
  • 引文作者姓名;
  • 引用。

由于这只是一个训练示例,因此我们将所有条目存储在 Python 列表中。 在实际的应用程序中,我们可能会使用数据库。

ai_quotes = [
    {
        "id": 0,
        "author": "Kevin Kelly",
        "quote": "The business plans of the next 10,000 startups are easy to forecast: " +
                 "Take X and add AI."
    },
    {
        "id": 1,
        "author": "Stephen Hawking",
        "quote": "The development of full artificial intelligence could " +
                 "spell the end of the human race… " +
                 "It would take off on its own, and re-design " +
                 "itself at an ever increasing rate. " +
                 "Humans, who are limited by slow biological evolution, " +
                 "couldn't compete, and would be superseded."
    },
    {
        "id": 2,
        "author": "Claude Shannon",
        "quote": "I visualize a time when we will be to robots what " +
                 "dogs are to humans, " +
                 "and I’m rooting for the machines."
    },
    {
        "id": 3,
        "author": "Elon Musk",
        "quote": "The pace of progress in artificial intelligence " +
                 "(I’m not referring to narrow AI) " +
                 "is incredibly fast. Unless you have direct " +
                 "exposure to groups like Deepmind, " +
                 "you have no idea how fast — it is growing " +
                 "at a pace close to exponential. " +
                 "The risk of something seriously dangerous " +
                 "happening is in the five-year timeframe." +
                 "10 years at most."
    },
    {
        "id": 4,
        "author": "Geoffrey Hinton",
        "quote": "I have always been convinced that the only way " +
                 "to get artificial intelligence to work " +
                 "is to do the computation in a way similar to the human brain. " +
                 "That is the goal I have been pursuing. We are making progress, " +
                 "though we still have lots to learn about " +
                 "how the brain actually works."
    },
    {
        "id": 5,
        "author": "Pedro Domingos",
        "quote": "People worry that computers will " +
                 "get too smart and take over the world, " +
                 "but the real problem is that they're too stupid " +
                 "and they've already taken over the world."
    },
    {
        "id": 6,
        "author": "Alan Turing",
        "quote": "It seems probable that once the machine thinking " +
                 "method had started, it would not take long " +
                 "to outstrip our feeble powers… " +
                 "They would be able to converse " +
                 "with each other to sharpen their wits. " +
                 "At some stage therefore, we should " +
                 "have to expect the machines to take control."
    },
    {
        "id": 7,
        "author": "Ray Kurzweil",
        "quote": "Artificial intelligence will reach " +
                 "human levels by around 2029. " +
                 "Follow that out further to, say, 2045, " +
                 "we will have multiplied the intelligence, " +
                 "the human biological machine intelligence " +
                 "of our civilization a billion-fold."
    },
    {
        "id": 8,
        "author": "Sebastian Thrun",
        "quote": "Nobody phrases it this way, but I think " +
                 "that artificial intelligence " +
                 "is almost a humanities discipline. It's really an attempt " +
                 "to understand human intelligence and human cognition."
    },
    {
        "id": 9,
        "author": "Andrew Ng",
        "quote": "We're making this analogy that AI is the new electricity." +
                 "Electricity transformed industries: agriculture, " +
                 "transportation, communication, manufacturing."
    }
]

现在我们需要创建一个 Quote 资源类来定义 API 端点的操作。 在类内部,您需要声明四个方法:get、post、put、delete。

让我们从 GET 方法开始

它可以通过指定 ID 来获取特定报价,如果未指定 ID,则可以获取随机报价。

class Quote(Resource):
    def get(self, id=0):
        if id == 0:
            return random.choice(ai_quotes), 200
        for quote in ai_quotes:
            if(quote["id"] == id):
                return quote, 200
        return "Quote not found", 404

如果 ID 包含默认值,则 GET 方法将返回随机引号,即调用方法时未指定ID。

如果已指定,则该方法会在引文中进行搜索并查找包含指定 ID 的引文。 如果未找到任何内容,则会显示消息“未找到报价,404”。

请记住:如果请求成功,该方法将返回 HTTP 状态 200;如果未找到记录,则返回 404。

现在让我们创建一个 POST 方法来将新报价添加到存储库

当您输入时,它将获取每个新报价的 ID。 此外,POST 将使用 reqparse 来解析请求正文中的参数(作者和引用文本)。

def post(self, id):
      parser = reqparse.RequestParser()
      parser.add_argument("author")
      parser.add_argument("quote")
      params = parser.parse_args()
      for quote in ai_quotes:
          if(id == quote["id"]):
              return f"Quote with id {id} already exists", 400
      quote = {
          "id": int(id),
          "author": params["author"],
          "quote": params["quote"]
      }
      ai_quotes.append(quote)
      return quote, 201

在上面的代码中,POST 方法接受报价 ID。 然后,使用 reqparse 从查询中检索作者和引文,并将它们存储在 params 字典中。

如果具有指定 ID 的报价已存在,该方法将显示相应的消息和代码 400。

如果尚未创建具有指定 ID 的引文,该方法将创建具有指定 ID 和作者以及其他参数的新记录。 然后,它将条目添加到 ai_quotes 列表中,并返回带有新报价的条目以及 201 代码。

现在我们创建一个 PUT 方法来更改存储库中的现有报价

def put(self, id):
      parser = reqparse.RequestParser()
      parser.add_argument("author")
      parser.add_argument("quote")
      params = parser.parse_args()
      for quote in ai_quotes:
          if(id == quote["id"]):
              quote["author"] = params["author"]
              quote["quote"] = params["quote"]
              return quote, 200
      
      quote = {
          "id": id,
          "author": params["author"],
          "quote": params["quote"]
      }
      
      ai_quotes.append(quote)
      return quote, 201

PUT 方法与前面的示例类似,采用 ID 和输入,并使用 reqparse 解析报价参数。

如果存在具有指定 ID 的引文,该方法将使用新参数对其进行更新,然后输出更新后的代码为 200 的引文。如果尚不存在具有指定 ID 的引文,则将创建一个代码为 201 的新记录。

最后,让我们创建一个 DELETE 方法来删​​除不再鼓舞人心的引用

def delete(self, id):
      global ai_quotes
      ai_quotes = [qoute for qoute in ai_quotes if qoute["id"] != id]
      return f"Quote with id {id} is deleted.", 200

此方法获取报价 ID 作为输入,并使用共享列表更新 ai_quotes 列表。

现在我们已经创建了所有方法,我们需要做的就是向 API 添加资源、设置路径并运行 Flask。

api.add_resource(Quote, "/ai-quotes", "/ai-quotes/", "/ai-quotes/<int:id>")
if __name__ == '__main__':
    app.run(debug=True)

我们的 REST API 服务已准备就绪!

接下来,我们可以使用以下命令在控制台中运行代码,将代码保存到 app.py 文件中:

python3 app.py

如果一切顺利,那么我们会得到这样的结果:

* 调试模式:开
* 继续运行 127.0.0.1:5000/(按CTRL+C退出)
* 重新启动统计
* 调试器已激活!
* 调试器密码:XXXXXXX

测试 API

API 创建完成后,需要对其进行测试。

这可以使用curl控制台实用程序或Insomnia REST客户端,或通过在Rapid API上发布API来完成。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

发布我们的 API

RapidAPI 是世界上最大的市场,拥有超过 10 个 API(以及大约 000 万开发人员)。

RapidAPI 不仅提供用于使用第三方 API 的单一接口,还使您能够快速轻松地发布自己的 API。

做吧,您首先需要将其发布到网络上的某个服务器上。 在我们的例子中,我们将使用 Heroku的。 使用它不会造成任何困难,(你可以在这里找到更多关于他的信息).

如何在 Heroku 上发布您的 API

1.安装Heroku。

第一步是注册并安装 Heroku 命令行界面 (CLI)。 这适用于 Ubuntu 16+。

sudo snap install heroku —经典

然后登录:

heroku登录

2. 添加必要的文件。

现在我们需要将要发布的文件添加到应用程序中的文件夹中:

  • requirements.txt 包含所需 Python 模块的列表;
  • Procfile,指定运行应用程序必须执行哪些命令;
  • .gitignore - 排除服务器上不需要的文件。

requirements.txt 文件将包含以下行:

  • 烧瓶
  • 烧瓶宁静
  • 独角兽

请注意,我们已将 Gunicorn(Python WSGI HTTP 服务器)添加到列表中,因为我们需要在服务器上运行我们的应用程序。

Procfile 将包含:

网址:gunicorn app:app

.gitignore 的内容:

*.pyc
__pycache__/

现在文件已创建,让我们初始化 git 存储库并提交:

git init
git add
git commit -m "First API commit"

3. 创建一个新的 Heroku 应用程序。

heroku create

我们将 master 分支推送到远程 Heroku 存储库:

git push heroku master

现在您可以使用以下命令打开 API 服务:

heroku ps:scale web=1
heroku open
 

该 API 将在以下位置提供: your-random-heroku-name.herokuapp.com/ai-quotes.

如何将 Python API 添加到 RapidAPI 市场

一旦您的 API 服务在 Heroku 上发布,您就可以将其添加到 Rapid API。 这里 详细的文档 关于这个话题。

1. 创建RapidAPI账户。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

注册一个免费帐户 - 这可以使用 Facebook、Google、GitHub 来完成。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

2. 将API添加到控制面板。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

3. 接下来,输入有关您的 API 的一般信息。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

4. 单击“添加 API”后,会出现一个新页面,您可以在其中输入有关我们 API 的信息。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

5. 现在您可以手动输入API端点或下载 招摇文件 使用开放API。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

好吧,现在我们需要在 Endpoints 页面上设置 API 的端点。 在我们的例子中,端点对应于 CRUD(获取、发布、放置、删除)的概念。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

接下来,您需要创建一个 GET AI Quote 端点,该端点显示随机报价(如果 ID 为默认)或指定 ID 的报价。

要创建端点,请单击“创建端点”按钮。

使用 Python 编写 API(使用 Flask 和 RapidAPI)

我们对所有其他 API 端点重复此过程。 就这样! 恭喜,您已经发布了 API!

如果一切顺利,API 页面将如下所示:

使用 Python 编写 API(使用 Flask 和 RapidAPI)

结论

在本文中,我们学习了使用 Python 创建自己的 RESTful API 服务的过程,以及将 API 发布到 Heroku 云并将其添加到 RapidAPI 目录的过程。

但测试版本只展示了API开发的基本原则——没有考虑安全性、容错性和可扩展性等细微差别。

在开发真正的 API 时,所有这些都需要考虑在内。

来源: habr.com

添加评论