Ide API na Python (ya na Flask na RapidAPI)

Ide API na Python (ya na Flask na RapidAPI)

Ọ bụrụ na ị na-agụ akụkọ a, ọ ga-abụ na ị maraworị nke ọma na ohere ndị na-emepe mgbe ị na-eji API (Application Programming Interface).

Site na ịgbakwunye otu n'ime ọtụtụ API ọha na ngwa gị, ị nwere ike ịgbatị arụmọrụ nke ngwa a ma ọ bụ tinye ya na data dị mkpa. Ma gịnị ma ọ bụrụ na ị mepụtala ihe pụrụ iche nke ịchọrọ ịkọrọ ndị obodo?

Azịza ya dị mfe: ị chọrọ mepụta API nke gị.

Ọ bụ ezie na nke a nwere ike ịdị ka ọrụ na-agwụ ike na mbụ, ọ dị nnọọ mfe. Anyị ga-egosi gị otu esi eji Python eme nke a.

Ihe ị chọrọ iji malite

Mmepe API chọrọ:

  • Python3;
  • karama - usoro dị mfe ma dị mfe iji mepụta ngwa weebụ;
  • Flask-zuru oke bụ ndọtị maka Flask nke na-enye gị ohere ịmepụta API REST ngwa ngwa yana jiri obere nhazi.

A na-arụ nwụnye site na iwu:

pip install flask-restful

Anyị na-akwado mmemme kpụ ọkụ n'ọnụ n'efu maka ndị mbido:
mmepe bot Telegram na C# — Ọgọst 26–28. Ngwa ngwa ngwa n'efu na-enye gị ohere ịghọta ka bots inyeaka si arụ ọrụ, njirimara nke ịrụ ọrụ na Telegram API na nuances ndị ọzọ. Ndị sonyere atọ kachasị elu ga-enweta 30 rubles site na Skillbox.

Tupu ịmalite

Anyị ga-emepụta API RESTful nwere isi Ọrụ CRUID.

Iji ghọta ọrụ ahụ nke ọma, ka anyị ghọta okwu abụọ ahụ a kpọtụrụ aha n'elu.

Kedu ihe bụ REST?

REST API (Nnyefe steeti nọchiri anya) bụ API na-eji arịrịọ HTTP gbanwere data.

API REST ga-emezurịrị ụfọdụ njirisi:

  • Nrụpụta ihe nkesa ndị ahịa: onye ahịa na-emekọrịta ihe na interface onye ọrụ, ihe nkesa na-ejikọkwa azụ azụ na ụlọ ahịa data. Onye ahịa na ihe nkesa nọọrọ onwe ya, onye ọ bụla n'ime ha nwere ike dochie ya iche na nke ọzọ.
  • Enweghị obodo - Ọ nweghị data ndị ahịa echekwara na sava ahụ. A na-echekwa ọnọdụ nnọkọ n'akụkụ ndị ahịa.
  • Cacheability - Ndị ahịa nwere ike ịchekwa nzaghachi nkesa iji melite arụmọrụ zuru ezu.

Kedu ihe bụ CRUD?

RAW bụ echiche mmemme nke na-akọwa omume anọ bụ isi (mepụta, gụọ, melite na ihichapụ).

Na REST API, ụdị arịrịọ na ụzọ arịrịọ na-ahụ maka omume dị ka biputere, nweta, tinye, ihichapụ.

Ugbu a anyị emesola usoro ndị bụ isi, anyị nwere ike ịmalite ịmepụta API.

Mmepe

Ka anyị mepụta ebe nchekwa okwu gbasara ọgụgụ isi. AI bụ otu n'ime teknụzụ na-eto ngwa ngwa taa, Python bụ ngwa a ma ama maka iji AI rụọ ọrụ.

Site na API a, onye nrụpụta Python nwere ike mụta ngwa ngwa gbasara AI wee nweta mmụọ ya site na mmezu ọhụrụ. Ọ bụrụ na onye nrụpụta nwere echiche bara uru na isiokwu a, ọ ga-enwe ike itinye ha na ebe nchekwa.

Ka anyị bido site na ibubata modul achọrọ na ịtọlite ​​Flask:

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

Na snippet a, Flask, Api na Resource bụ klaasị anyị chọrọ.

Reqparse bụ ihe nleba anya nke arịrịọ Flask-RESTful… Ị ga-achọkwa modul random iji gosipụta ngụpụta enweghị usoro.

Ugbu a, anyị ga-emepụta ebe nchekwa nke okwu gbasara AI.

Ndenye repo ọ bụla ga-enwe:

  • NJ dijitalụ;
  • aha onye dere okwu;
  • see okwu.

Ebe ọ bụ na nke a bụ naanị ọmụmaatụ mmụta, anyị ga-echekwa ndenye niile na ndepụta Python. Na ngwa n'ezie, anyị nwere ike iji nchekwa data kama.

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."
    }
]

Ugbu a, anyị kwesịrị ịmepụta klas akụrụngwa Quote nke ga-akọwapụta ọrụ nke njedebe API anyị. A ghaghị ikwupụta ụzọ anọ n'ime klaasị: nweta, biputere, tinye, hichapụ.

Ka anyị jiri usoro GET bido

Ọ na-enye gị ohere ịnweta ọnụ ọgụgụ akọwapụtara site n'ịkọwapụta ID ya, ma ọ bụ ọnụ ọgụgụ na-enweghị usoro ma ọ bụrụ na enweghị ID akọwapụtara.

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

Usoro GET na-eweghachite nkwụghachi ụgwọ ma ọ bụrụ na ID ahụ nwere uru ndabara, ya bụ. Edobeghị ID mgbe ị na-akpọ usoro.

Ọ bụrụ na edobere ya, mgbe ahụ usoro ahụ na-achọgharị n'etiti nkwuputa wee chọta nke nwere NJ enyere. Ọ bụrụ na achọtaghị ihe ọ bụla, a ga-egosipụta ozi "Quote not found, 404".

Cheta, usoro a na-eweghachi ọkwa HTTP nke 200 ma ọ bụrụ na arịrịọ ahụ gara nke ọma yana 404 ma ọ bụrụ na ahụghị ntinye.

Ugbu a, ka anyị mepụta usoro POST iji gbakwunye ngụ ọhụrụ na ebe nchekwa

Ọ ga-enweta id nke okwu ọhụrụ ọ bụla ka ị na-ede. Na mgbakwunye, POST ga-eji reqparse tụgharịa paramita ga-abanye na ahụ arịrịọ (onye ode akwụkwọ na nhota ederede).

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

Na koodu dị n'elu, usoro POST nabatara NJ ntinye akwụkwọ. Mgbe ahụ, na-eji reqparse, ọ weghachitere odee wee kwuo okwu site na arịrịọ ahụ, na-echekwa ha na akwụkwọ ọkọwa okwu params.

Ọ bụrụ na ntinye akwụkwọ nwere ID akọwapụtara adịlarị, usoro ahụ na-egosipụta ozi kwesịrị ekwesị yana koodu 400.

Ọ bụrụ na emebebeghị ntinye aka na ID akọwapụtara, usoro a na-emepụta ntinye ọhụrụ yana ID na onye edemede akọwapụtara, yana paramita ndị ọzọ. Ọ na-agbakwụnye ntinye na ndepụta ai_quotes wee weghachi ntinye na ntinye ọhụrụ yana koodu 201.

Ugbu a, anyị na-emepụta usoro PUT iji gbanwee ntinye dị na ebe nchekwa

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

Usoro PUT, dị ka ihe atụ gara aga, na-ewere NJ yana ntinye wee tụgharịa paramita ngụpụta site na iji reqparse.

Ọ bụrụ na ntinye akwụkwọ nwere ID akọwapụtara, usoro ahụ ga-emelite ya na paramita ọhụrụ wee wepụta ntinye emelitere na koodu 200. Ọ bụrụ na enweghị ntinye aka na ID akọwapụtara, a ga-emepụta ndekọ ọhụrụ nwere koodu 201.

N'ikpeazụ, ka anyị mepụta usoro ihichapụ iji wepụ okwu na-adịghị akpali akpali.

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

Usoro a na-ewe ID ngụ dị ka ntinye ma na-emelite ndepụta ai_quotes site na iji ndepụta ekekọrịtara.

Ugbu a anyị emepụtala ụzọ niile, naanị ihe anyị ga-eme bụ ịgbakwunye akụ na API, tọọ ụzọ, wee gbaa Flask.

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

Ọrụ API REST anyị adịla njikere!

Na-esote, anyị nwere ike ichekwa koodu ahụ na faịlụ app.py site na iji iwu ahụ na-agba ya na console:

python3 app.py

Ọ bụrụ na ihe niile dị mma, anyị ga-enweta ihe dị ka nke a:

* Ụdị nbipu: agbanwuru
* Na-aga n'ihu 127.0.0.1:5000/ (pịa CTRL+C ka ịkwụsị)
* Malitegharịa ekwentị na stat
* Debugger na-arụ ọrụ!
* PIN onye nbibi: XXXXXXX

Na-anwale API

Mgbe emechara API, ọ dị mkpa ka a nwalee ya.

Enwere ike ime nke a site na iji ihe njikwa curl ma ọ bụ onye ahịa Insomnia REST, ma ọ bụ site na ibipụta API na ngwa ngwa API.

Ide API na Python (ya na Flask na RapidAPI)

Na-ebipụta API anyị

RapidAPI bụ nnukwu ahịa n'ụwa nwere ihe karịrị API 10 (na ihe dị ka nde ndị mmepe 000).

RapidAPI abụghị naanị na-enye otu interface maka ịrụ ọrụ na API ndị ọzọ, kamakwa na-enye gị ohere ibipụta API nke gị ngwa ngwa na ngwa ngwa.

Iji ime nke a, ị ga-ebu ụzọ bipụta ya na ụfọdụ ihe nkesa na netwọk. N'ọnọdụ anyị, anyị ga-eji Heroku. Iso ya na-arụ ọrụ ekwesịghị ịkpata nsogbu ọ bụla, (ị nwere ike ịmatakwu gbasara ya ebe a).

Otu esi ebipụta API gị na Heroku

1. Wụnye Heroku.

Nzọụkwụ mbụ bụ ịdebanye aha na wụnye Heroku Command Line Interface (CLI). Nke a na-arụ ọrụ na Ubuntu 16+.

sudo snap wụnye heroku --classic

Mgbe ahụ, anyị na-abanye:

heroku nbanye

2. Tinye faịlụ ndị dị mkpa.

Ugbu a, anyị kwesịrị ịgbakwunye faịlụ ndị anyị ga-ebipụta na nchekwa na ngwa anyị:

  • bukatun.txt nwere ndepụta nke modul Python achọrọ;
  • Procfile, nke na-akọwapụta iwu ga-emerịrị iji mee ngwa ahụ;
  • .gitignore - ewepu faịlụ na-adịghị mkpa na ihe nkesa.

Faịlụ chọrọ.txt ga-enwe ahịrị ndị a:

  • agba
  • flask-ezu ike
  • gunicorn

Biko mara na anyị agbakwunyela gunicorn (Python WSGI HTTP Server) na ndepụta ahụ n'ihi na anyị kwesịrị ịme ngwa anyị na sava ahụ.

Profaịlụ ga-enwe:

webụ: ngwa gunicorn: ngwa

Ọdịnaya nke .gitignore:

*.pyc
__pycache__/

Ugbu a emepụtara faịlụ ndị ahụ, ka anyị bido git repo wee mee:

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

3. Mepụta ngwa Heroku ọhụrụ.

heroku create

Ịkwanye alaka ụlọ ọrụ na Heroku repo dịpụrụ adịpụ:

git push heroku master

Ugbu a ị nwere ike ịmalite site na iji iwu ndị a:

heroku ps:scale web=1
heroku open
 

API ga-adị na your-random-heroku-name.herokuapp.com/ai-quotes.

Otu esi etinye Python API gị n'ahịa RapidAPI

Ozugbo ebipụtara ọrụ API na Heroku, ị nwere ike itinye ya na ngwa ngwa API. Ebe a akwụkwọ zuru ezu n'okwu a.

1. Mepụta akaụntụ RapidAPI.

Ide API na Python (ya na Flask na RapidAPI)

Anyị na-edebanye aha akaụntụ efu - enwere ike ime nke a site na iji Facebook, Google, GitHub.

Ide API na Python (ya na Flask na RapidAPI)

2. Tinye API na njikwa njikwa.

Ide API na Python (ya na Flask na RapidAPI)

3. Ọzọ, tinye ozi izugbe gbasara API gị.

Ide API na Python (ya na Flask na RapidAPI)

4. Mgbe ịpịrị "Tinye API" ibe ọhụrụ pụtara ebe ị nwere ike itinye ozi gbasara API anyị.

Ide API na Python (ya na Flask na RapidAPI)

5. Ugbu a ị nwere ike iji aka tinye njedebe API, ma ọ bụ budata swagger faịlụ na-eji OpenAPI.

Ide API na Python (ya na Flask na RapidAPI)

Ọ dị mma, ugbu a ịkwesịrị ịtọ ebe njedebe nke API anyị na ibe ngwụcha. N'ọnọdụ anyị, njedebe njedebe kwekọrọ na echiche nke CRUD (nweta, biputere, tinye, hichapụ).

Ide API na Python (ya na Flask na RapidAPI)

Na-esote, ịkwesịrị ịmepụta njedebe GET AI Quote nke na-egosiputa ntinye aka (ọ bụrụ na ID ahụ bụ nke ndabara) ma ọ bụ ntinye maka ID akọwapụtara.

Iji mepụta ebe njedebe, ịkwesịrị ịpị bọtịnụ "Mepụta njedebe njedebe".

Ide API na Python (ya na Flask na RapidAPI)

Anyị na-emegharị usoro a maka njedebe njedebe API ndị ọzọ. Ọ gwụla! Ekele, ị bipụtala API gị!

Ọ bụrụ na ihe niile na-aga nke ọma, ibe API ga-adị ka nke a:

Ide API na Python (ya na Flask na RapidAPI)

nkwubi

N'ime edemede a, anyị jere ije na usoro nke ịmepụta ọrụ RESTful API nke anyị na Python, yana usoro nke ibipụta API na igwe ojii Heroku ma tinye ya na ndekọ RapidAPI.

Ma na ụdị ule ahụ, ọ bụ naanị ụkpụrụ ndị bụ isi nke mmepe API ka egosiri - adịghị atụle nuances dị ka nchekwa, ntachi obi na scalability.

Mgbe ị na-emepụta ezigbo API, a ga-eburu n'uche ihe ndị a niile.

isi: www.habr.com

Tinye a comment