Sau API hauv Python (nrog Flask thiab RapidAPI)

Sau API hauv Python (nrog Flask thiab RapidAPI)

Yog tias koj tab tom nyeem tsab xov xwm no, tej zaum koj twb paub txog qhov muaj peev xwm uas tuaj nrog siv API (Application Programming Interface).

Los ntawm kev ntxiv ib qho ntawm ntau qhib APIs rau koj daim ntawv thov, koj tuaj yeem txuas ntxiv kev ua haujlwm ntawm daim ntawv thov lossis txhawb nws nrog cov ntaub ntawv tsim nyog. Tab sis yuav ua li cas yog tias koj tsim ib qho tshwj xeeb uas koj xav qhia rau zej zog?

Cov lus teb yog yooj yim: koj xav tau tsim koj tus kheej API.

Txawm hais tias qhov no yuav zoo li ua haujlwm nyuaj thaum xub thawj, nws yog qhov yooj yim. Peb yuav qhia koj yuav ua li cas ua qhov no siv Python.

Dab tsi koj yuav tsum tau pib

Txhawm rau tsim API koj xav tau:

  • Python 3;
  • Nplaim taws - lub moj khaum yooj yim thiab siv tau yooj yim rau kev tsim cov ntawv thov web;
  • Flask-RESTful yog qhov txuas ntxiv rau Flask uas tso cai rau koj los tsim REST API sai sai thiab nrog kev teeb tsa tsawg.

Installation yog ua nrog cov lus txib:

pip install flask-restful

Peb pom zoo kom muaj ib chav kawm dawb intensive programming rau beginners:
Kev txhim kho Telegram bot hauv C # β€” Aug 26–28. Ib chav kawm pub dawb uas tso cai rau koj nkag siab tias tus pab bots ua haujlwm li cas, qhov tshwj xeeb ntawm kev ua haujlwm nrog Telegram API thiab lwm yam nuances. Peb tus neeg tuaj koom zoo tshaj plaws yuav tau txais 30 rubles los ntawm Skillbox.

Ua ntej koj pib

Peb tab tom yuav tsim RESTful API nrog rau theem pib CRUID kev ua haujlwm.

Txhawm rau kom nkag siab txog txoj haujlwm, cia peb nkag siab ob nqe lus hais saum toj no.

REST yog dab tsi?

REST API (Sawv cev Lub Xeev Hloov) yog API uas siv HTTP thov los pauv cov ntaub ntawv.

REST APIs yuav tsum ua tau raws li qee yam kev cai:

  • Client-server architecture: Tus neeg siv khoom cuam tshuam nrog tus neeg siv interface, thiab lub server cuam tshuam nrog lub backend thiab cov ntaub ntawv khaws cia. Cov neeg siv khoom thiab cov neeg rau zaub mov muaj kev ywj pheej, ib qho ntawm lawv tuaj yeem hloov pauv ntawm lwm tus.
  • Stateless - tsis muaj cov ntaub ntawv tus neeg siv khoom khaws cia ntawm lub server. Session state yog khaws cia rau ntawm tus neeg siv khoom.
  • Cacheability - Cov neeg siv khoom tuaj yeem cache cov lus teb rau server los txhim kho kev ua haujlwm tag nrho.

CRUD yog dab tsi?

RAW yog lub ntsiab lus programming uas piav qhia txog plaub qhov kev nqis tes ua (tsim, nyeem, hloov tshiab thiab rho tawm).

Hauv REST API, thov hom thiab thov txoj hauv kev yog lub luag haujlwm rau kev ua xws li tshaj tawm, tau txais, tso, rho tawm.

Tam sim no peb nkag siab cov ntsiab lus yooj yim, peb tuaj yeem pib tsim API.

Kev loj hlob

Cia peb tsim ib qho chaw cia khoom ntawm cov lus hais txog kev txawj ntse. AI yog ib qho ntawm cov thev naus laus zis loj tshaj plaws niaj hnub no, thiab Python yog cov cuab yeej nrov rau kev ua haujlwm nrog AI.

Nrog rau qhov API no, tus tsim tawm Python tuaj yeem tau txais cov ntaub ntawv hais txog AI sai thiab tau txais kev tshoov siab los ntawm kev nce qib tshiab. Yog tias tus tsim tawm muaj kev xav zoo rau lub ntsiab lus no, nws yuav muaj peev xwm ntxiv rau hauv qhov chaw cia khoom.

Cia peb pib los ntawm kev xa cov qauv tsim nyog thiab teeb tsa Flask:

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

Hauv cov ntawv no, Flask, Api thiab Resource yog cov chav kawm uas peb xav tau.

Reqparse yog Flask-RESTful query parsing interface... Koj tseem yuav xav tau ib qho random module los tso saib cov lus tsocai.

Tam sim no peb yuav tsim ib lub chaw cia khoom ntawm cov lus hais txog AI.

Txhua repo nkag yuav muaj:

  • digital ID;
  • lub npe ntawm tus sau cov lus;
  • nqe lus.

Txij li qhov no tsuas yog ib qho piv txwv kev cob qhia, peb yuav khaws tag nrho cov ntawv nkag hauv Python daim ntawv teev npe. Hauv daim ntawv thov tiag tiag, peb yuav zoo li siv database hloov.

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

Tam sim no peb yuav tsum tsim kom muaj Quote cov chav kawm uas yuav txhais cov haujlwm ntawm peb cov API kawg. Hauv chav kawm koj yuav tsum tshaj tawm plaub txoj hauv kev: tau txais, tshaj tawm, tso, rho tawm.

Cia peb pib nrog GET txoj kev

Nws ua rau nws muaj peev xwm tau txais ib qho kev tsocai tshwj xeeb los ntawm kev qhia nws tus ID, lossis ib qho kev tsocai yog tias tus ID tsis tau teev tseg.

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

Txoj kev GET xa rov qab ib qho kev tsocai yog tias tus ID muaj tus nqi qub, piv txwv li. tsis muaj ID tau teev tseg thaum hu rau txoj kev.

Yog tias nws tau teev tseg, ces txoj kev tshawb nrhiav ntawm cov ntawv sau thiab pom ib qho uas muaj tus ID teev. Yog tias tsis muaj dab tsi pom, cov lus "Quote tsis pom, 404" yuav tshwm sim.

Nco ntsoov: txoj kev rov qab HTTP txheej xwm ntawm 200 yog tias qhov kev thov tau ua tiav thiab 404 yog tias tsis pom cov ntaub ntawv.

Tam sim no cia peb tsim POST txoj hauv kev ntxiv cov lus tsocai tshiab rau lub chaw cia khoom

Nws yuav tau txais tus ID ntawm txhua qhov kev tsocai tshiab thaum koj ntaus. Tsis tas li ntawd, POST yuav siv reqparse los txheeb xyuas qhov tsis sib xws uas yuav nkag mus rau hauv lub cev thov (tus sau thiab cov ntawv sau cia).

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

Hauv cov cai saum toj no, POST txoj kev lees txais tus lej ID. Tom qab ntawd, siv reqparse, nws tau muab cov neeg sau ntawv thiab cov ntawv sau los ntawm cov lus nug, khaws cia rau hauv phau ntawv txhais lus params.

Yog hais tias ib qho kev tsocai nrog tus ID uas tau teev tseg twb muaj lawm, txoj kev qhia cov lus sib raug thiab code 400.

Yog tias daim ntawv teev npe nrog tus ID tshwj xeeb tseem tsis tau tsim, txoj kev tsim cov ntaub ntawv tshiab nrog tus ID thiab tus sau, nrog rau lwm yam tsis muaj. Tom qab ntawd nws ntxiv qhov nkag mus rau ai_quotes daim ntawv teev npe thiab xa rov qab nkag nrog cov lus tsocai tshiab nrog rau 201 code.

Tam sim no peb tsim PUT txoj hauv kev los hloov qhov kev tsocai uas twb muaj lawm hauv qhov chaw cia khoom

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

Txoj kev PUT, zoo ib yam li qhov piv txwv yav dhau los, siv ID thiab cov tswv yim thiab txheeb xyuas cov lus qhia tsis siv reqparse.

Yog tias muaj ib daim ntawv teev npe nrog tus ID uas tau teev tseg, txoj hauv kev yuav hloov kho nrog cov kev txwv tshiab thiab tom qab ntawd tso tawm cov ntaub ntawv hloov tshiab nrog code 200. Yog tias tsis muaj qhov citation nrog tus ID tau teev tseg, cov ntaub ntawv tshiab nrog code 201 yuav raug tsim.

Thaum kawg, cia peb tsim txoj kev DELETE kom tshem tawm cov lus tsocai uas tsis muaj kev tshoov siab lawm

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

Txoj kev no tau txais daim ntawv tsocai ID raws li kev tawm tswv yim thiab hloov kho cov npe ai_quotes siv cov npe sib koom.

Tam sim no peb tau tsim txhua txoj hauv kev, txhua yam peb yuav tsum ua tsuas yog ntxiv cov peev txheej rau API, teeb txoj hauv kev, thiab khiav Flask.

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

Peb qhov REST API Service yog npaj txhij!

Tom ntej no, peb tuaj yeem khaws cov cai rau cov ntaub ntawv app.py los ntawm kev khiav nws hauv console siv cov lus txib:

python3 app.py

Yog tias txhua yam zoo, peb yuav tau txais qee yam zoo li no:

* Debug hom: nyob rau
* Khiav rau 127.0.0.1: 5000 / (Nias CTRL + C kom tawm)
* Rov pib dua nrog stat
* Debugger ua haujlwm!
* Debugger PIN: XXXXXXXXXX

Kev xeem API

Thaum API tau tsim, nws yuav tsum tau sim.

Qhov no tuaj yeem ua tiav siv cov khoom siv hluav taws xob curl lossis Insomnia REST tus neeg siv, lossis los ntawm kev tshaj tawm API ntawm Rapid API.

Sau API hauv Python (nrog Flask thiab RapidAPI)

Tshaj tawm peb API

RapidAPI yog lub ntiaj teb kev lag luam loj tshaj plaws nrog ntau dua 10 APIs (thiab kwv yees li 000 lab tus tsim tawm).

RapidAPI tsis tsuas yog muab ib qho kev sib txuas rau kev ua haujlwm nrog cov neeg thib peb APIs, tab sis kuj muab koj lub peev xwm los luam tawm koj tus kheej API sai thiab yooj yim.

Yuav kom ua nws, koj thawj zaug yuav tsum tau tshaj tawm nws ntawm qee tus neeg rau zaub mov hauv lub network. Hauv peb qhov xwm txheej peb yuav siv Heroku. Ua haujlwm nrog nws yuav tsum tsis txhob ua rau muaj teeb meem, (koj tuaj yeem paub ntau ntxiv txog nws ntawm no).

Yuav Ua Li Cas Tshaj Tawm Koj API ntawm Heroku

1. Nruab Heroku.

Thawj kauj ruam yog sau npe thiab nruab Heroku Command Line Interface (CLI). Qhov no ua haujlwm ntawm Ubuntu 16+.

sudo snap nruab heroku -classic

Tom qab ntawd nkag mus:

heroku tus ID nkag mus

2. Ntxiv cov ntaub ntawv tsim nyog.

Tam sim no peb yuav tsum tau ntxiv cov ntaub ntawv yuav tsum luam tawm mus rau ib daim nplaub tshev hauv peb daim ntawv thov:

  • require.txt nrog ib daim ntawv teev cov yuav tsum tau Python modules;
  • Procfile, uas qhia meej tias cov lus txib twg yuav tsum tau ua kom khiav daim ntawv thov;
  • .gitignore - tshem tawm cov ntaub ntawv uas tsis xav tau ntawm lub server.

Cov ntaub ntawv xav tau.txt yuav muaj cov kab hauv qab no:

  • hwj
  • haus dej cawv
  • phom phom

Thov nco ntsoov tias peb tau ntxiv rab phom (Python WSGI HTTP Server) rau hauv daim ntawv vim tias peb yuav tsum tau khiav peb daim ntawv thov ntawm lub server.

Procfile yuav muaj:

web: gunicorn app: app

Cov ntsiab lus ntawm .gitignore:

*.pyc
__pycache__/

Tam sim no cov ntaub ntawv raug tsim, cia peb pib lub git repo thiab cog lus:

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

3. Tsim ib daim ntawv thov Heroku tshiab.

heroku create

Peb thawb tus tswv ceg mus rau tej thaj chaw deb Heroku repo:

git push heroku master

Tam sim no koj tuaj yeem pib los ntawm kev qhib API Service siv cov lus txib:

heroku ps:scale web=1
heroku open
 

API yuav muaj nyob ntawm koj-random-heroku-name.herokuapp.com/ai-quotes.

Yuav ua li cas ntxiv koj Python API rau RapidAPI kev lag luam

Thaum koj qhov kev pabcuam API tau tshaj tawm ntawm Heroku, koj tuaj yeem ntxiv nws mus rau Rapid API. Ntawm no cov ntaub ntawv ntxaws ntawm lub ncauj lus no.

1. Tsim ib tus account RapidAPI.

Sau API hauv Python (nrog Flask thiab RapidAPI)

Sau npe tus account pub dawb - qhov no tuaj yeem ua tiav siv Facebook, Google, GitHub.

Sau API hauv Python (nrog Flask thiab RapidAPI)

2. Ntxiv API rau lub vaj huam sib luag tswj.

Sau API hauv Python (nrog Flask thiab RapidAPI)

3. Tom ntej no, sau cov ntaub ntawv dav dav txog koj qhov API.

Sau API hauv Python (nrog Flask thiab RapidAPI)

4. Tom qab txhaj "Ntxiv API" nplooj ntawv tshiab tshwm nyob qhov twg koj tuaj yeem sau cov ntaub ntawv hais txog peb API.

Sau API hauv Python (nrog Flask thiab RapidAPI)

5. Tam sim no koj tuaj yeem nkag mus rau API kawg lossis rub tawm swagger-file siv OpenAPI.

Sau API hauv Python (nrog Flask thiab RapidAPI)

Zoo, tam sim no peb yuav tsum teeb tsa qhov kawg ntawm peb API ntawm nplooj ntawv Endpoints. Hauv peb qhov xwm txheej, cov ntsiab lus kawg sib haum rau lub tswv yim ntawm CRUD (tau, tshaj tawm, tso, rho tawm).

Sau API hauv Python (nrog Flask thiab RapidAPI)

Tom ntej no, koj yuav tsum tsim kom tau GET AI Quote qhov kawg uas qhia txog qhov kev tsocai random (yog tias tus ID yog lub neej ntawd) lossis nqe lus rau tus ID.

Txhawm rau tsim qhov kawg, nyem lub pob "Create Endpoint".

Sau API hauv Python (nrog Flask thiab RapidAPI)

Peb rov ua qhov txheej txheem no rau tag nrho lwm qhov kawg API. Yog tag nrho! Nrog koj zoo siab, koj tau luam tawm koj API!

Yog tias txhua yam zoo, nplooj ntawv API yuav zoo li no:

Sau API hauv Python (nrog Flask thiab RapidAPI)

xaus

Hauv tsab xov xwm no, peb tau kawm cov txheej txheem ntawm kev tsim koj tus kheej RESTful API Service hauv Python, nrog rau cov txheej txheem luam tawm API rau Heroku huab thiab ntxiv rau RapidAPI phau ntawv qhia.

Tab sis qhov kev sim version pom tsuas yog cov hauv paus ntsiab lus ntawm API txoj kev loj hlob - nuances xws li kev ruaj ntseg, txhaum cai thiab scalability tsis tau txiav txim siab.

Thaum tsim API tiag tiag, txhua qhov no yuav tsum tau muab coj los rau hauv tus account.

Tau qhov twg los: www.hab.com

Ntxiv ib saib