使用 Python 編寫 API(使用 Flask 和 RapidAPI)

使用 Python 編寫 API(使用 Flask 和 RapidAPI)

如果您正在閱讀本文,您可能已經熟悉使用 API(應用程序編程接口)時所帶來的可能性。

通過將眾多公共 API 之一添加到您的應用程序,您可以擴展該應用程序的功能或為其補充必要的數據。 但是,如果您開發了一項獨特的功能並想與社區分享怎麼辦?

答案很簡單:你需要 創建您自己的 API.

雖然乍一看這似乎是一項艱鉅的任務,但實際上非常簡單。 我們將向您展示如何使用 Python 執行此操作。

您需要什麼才能開始

API開發需要:

  • Python 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 請求解析接口...您還需要 random 模塊來顯示隨機報價。

現在我們將創建一個有關人工智能的引言存儲庫。

每個存儲庫條目將包含:

  • 數字身份證;
  • 引文作者姓名;
  • 引用。

由於這只是一個學習示例,因此我們將所有條目存儲在 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 --classic

然後我們登錄:

heroku登錄

2. 添加必要的文件。

現在我們需要將要發布的文件添加到應用程序中的文件夾中:

  • requirements.txt 包含所需 Python 模塊的列表;
  • Procfile,它指定必須執行哪些命令才能運行應用程序;
  • .gitignore - 排除服務器上不需要的文件。

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

  • 燒瓶
  • 燒瓶寧靜
  • 獨角獸

請注意,我們已將 Gunicorn(Python WSGI HTTP 服務器)添加到列表中,因為我們需要在服務器上運行我們的應用程序。

Procfile 將包含:

網絡:gunicorn 應用程序:應用程序

.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 時,所有這些都必須考慮在內。

來源: www.habr.com

添加評論