Ho ngola API ho Python (ka Flask le RapidAPI)

Ho ngola API ho Python (ka Flask le RapidAPI)

Haeba u bala sengoloa sena, mohlomong u se u ntse u tloaelane le menyetla e bulehang ha u sebelisa API (Application Programming Interface).

Ka ho kenyelletsa e 'ngoe ea li-API tse ngata tsa sechaba ts'ebelisong ea hau, o ka eketsa ts'ebetso ea ts'ebeliso ena kapa oa e eketsa ka lintlha tse hlokahalang. Empa ho thoe'ng haeba u na le tšobotsi e ikhethang eo u batlang ho e arolelana le sechaba?

Karabo e bonolo: oa hloka theha API ea hau.

Le hoja sena se ka bonahala e le mosebetsi o boima qalong, ha e le hantle se bonolo haholo. Re tla u bontša mokhoa oa ho etsa sena ka Python.

Seo u se hlokang ho qala

Ntlafatso ea API e hloka:

  • Python3;
  • Flask - moralo o bonolo le o bonolo oa ho theha lits'ebetso tsa webo;
  • Botlolo-KGOTSO ke katoloso ea Flask e u lumellang hore u thehe REST API kapele le ka ho seta ho fokolang.

Ho kenya ho etsoa ka taelo:

pip install flask-restful

Re khothaletsa lenaneo le matla la mahala bakeng sa ba qalang:
Nts'etsopele ea bot ea telegraph ho C # - la 26-28 August. Sesebelisoa se matla sa mahala se u lumellang ho utloisisa hore na bots ea mothusi e sebetsa joang, likarolo tsa ho sebetsa le Telegraph API le lintlha tse ling. Barupeluoa ba bararo ba holimo ba tla fumana li-ruble tse 30 ho tsoa ho Skillbox.

Pele o qala

Re tlo theha RESTful API e nang le motheo Mosebetsi oa CRUID.

Ho utloisisa mosebetsi ka botlalo, a re utloisiseng mantsoe a mabeli a boletsoeng ka holimo.

REST ke eng?

REST API (Representational State Transfer) ke API e sebelisang likopo tsa HTTP ho fapanyetsana lintlha.

REST APIs e tlameha ho fihlela maemo a itseng:

  • Mehaho ea bareki-server: moreki o sebelisana le sebopeho sa mosebelisi, 'me seva se sebelisana le polokelo ea morao-rao le data. Moreki le seva li ikemetse, leha e le efe ea tsona e ka nkeloa sebaka ka thoko ho tse ling.
  • Stateless - Ha ho data ea bareki e bolokiloeng ho seva. Boemo ba seboka bo bolokiloe ka lehlakoreng la bareki.
  • Cacheability - Bareki ba ka boloka likarabo tsa seva ho ntlafatsa ts'ebetso ka kakaretso.

CRUD ke eng?

MOKHOA ke mohopolo oa lenaneo o hlalosang liketso tse 'ne tsa mantlha (etsa, bala, ntlafatsa le ho hlakola).

Ho REST API, mefuta ea kopo le mekhoa ea kopo e ikarabella bakeng sa liketso tse kang poso, fumana, beha, hlakola.

Kaha joale re se re sebetsane le mantsoe a mantlha, re ka qala ho theha API.

Ntlafatso

Ha re theheng polokelo ea mantsoe a qotsitsoeng mabapi le bohlale ba maiketsetso. AI ke e 'ngoe ea mahlale a ntseng a hola ka potlako kajeno,' me Python ke sesebelisoa se tsebahalang sa ho sebetsa le AI.

Ka API ena, moqapi oa Python a ka ithuta kapele ka AI mme a khothaletsoa ke katleho e ncha. Haeba moqapi a e-na le mehopolo ea bohlokoa tabeng ena, o tla khona ho e kenya sebakeng sa polokelo.

Ha re qale ka ho kenya li-module tse hlokahalang le ho theha Flask:

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

Ka snippet ena, Flask, Api le Resource ke litlelase tseo re li hlokang.

Reqparse is a Flask-RESTful request parsing interface... U tla boela u hloke mojule o sa reroang ho hlahisa qotso e sa reroang.

Joale re tla theha polokelo ea mantsoe a qotsitsoeng ka AI.

E 'ngoe le e' ngoe ea repo e tla ba le:

  • ID ea digital;
  • lebitso la mongodi wa qotso;
  • qotsa.

Kaha ona ke mohlala feela oa ho ithuta, re tla boloka lingoloa tsohle lethathamong la Python. Ts'ebetsong ea 'nete, re ka sebelisa database ho fapana le hoo.

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

Joale re hloka ho theha sehlopha sa lisebelisoa tsa Quote se tla hlalosa ts'ebetso ea liphetho tsa rona tsa API. Mekhoa e mene e tlameha ho phatlalatsoa ka har'a sehlopha: fumana, beha, beha, hlakola.

Ha re qaleng ka mokhoa oa GET

E u lumella ho fumana qotso e itseng ka ho hlakisa ID ea eona, kapa qotso e sa reroang haeba ho se ID e boletsoeng.

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

Mokhoa oa GET o khutlisa qotso e sa reroang haeba ID e na le boleng ba kamehla, ke hore. ID e ne e sa behoa ha o letsetsa mokhoa.

Haeba e behiloe, joale mokhoa o batla har'a mantsoe a qotsitsoeng ebe o fumana e nang le ID e fanoeng. Haeba ho se letho le fumanoeng, molaetsa o reng "Quote ha e fumanehe, 404" e tla hlaha.

Hopola, mokhoa ona o khutlisa boemo ba HTTP ba 200 haeba kopo e atlehile le 404 haeba ho kena ho sa fumanoe.

Joale ha re theheng mokhoa oa POST oa ho kenyelletsa qotso e ncha sebakeng sa polokelo

E tla fumana id ea qotso e 'ngoe le e 'ngoe e ncha ha u ntse u ngola. Ntle le moo, POST e tla sebelisa reqparse ho hlophisa liparamente tse tla kena sehlopheng sa kopo (mongoli le mongolo oa qotsa).

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

Khoutung e kaholimo, mokhoa oa POST o amohetse ID ea quote. Joale, ka ho sebelisa reqparse, e ile ea khutlisa sengoli le ho qotsa kopo, ea li boloka bukeng ea params.

Haeba qotsulo e nang le ID e boletsoeng e se e ntse e le teng, mokhoa o bonts'a molaetsa o nepahetseng le khoutu ea 400.

Haeba quote e nang le ID e boletsoeng e e-s'o thehoe, mokhoa ona o etsa hore ho be le mokhoa o mocha ka ID e boletsoeng le mongoli, hammoho le litekanyo tse ling. E ntan'o eketsa lethathamo la ai_quotes mme e khutlisa keno ka quote e ncha hammoho le khoutu ea 201.

Joale re theha mokhoa oa PUT oa ho fetola qotso e teng sebakeng sa polokelo

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

Mokhoa oa PUT, o ts'oanang le mohlala o fetileng, o nka ID le ho kenya letsoho ebe o fetisa litekanyetso tsa qotsulo o sebelisa reqparse.

Haeba qotso e nang le ID e boletsoeng e le teng, mokhoa o tla e nchafatsa ka li-parameter tse ncha ebe o ntša quote e nchafalitsoeng ka khoutu ea 200. Haeba ho se na quote e nang le ID e boletsoeng, rekoto e ncha e nang le khoutu ea 201 e tla etsoa.

Qetellong, ha re theheng mokhoa oa DELETE oa ho tlosa qotso e seng e sa khothaletse.

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

Mokhoa ona o nka ID ea qotsulo e le ho kenya letsoho le ho ntlafatsa lenane la ai_quotes o sebelisa lenane le arolelanoang.

Kaha joale re thehile mekhoa eohle, seo re hlokang ho se etsa feela ke ho eketsa sesebelisoa ho API, ho beha tsela, le ho tsamaisa Flask.

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

Tšebeletso ea rona ea REST API e se e loketse!

Ka mor'a moo, re ka boloka khoutu faeleng ea app.py ka ho e sebelisa ka har'a console ka taelo:

python3 app.py

Haeba tsohle li lokile, re tla fumana ntho e kang ena:

* Mokhoa oa ho lokisa: buletsoe
* Ho matha pele 127.0.0.1:5000/ (Tobetsa CTRL+C ho tlohela)
* Ho qala hape ka stat
* Debugger e ea sebetsa!
* PIN ea Debugger: XXXXXXX

Ho hlahloba API

Ka mor'a hore API e thehoe, e hloka ho lekoa.

Sena se ka etsoa ho sebelisoa sesebelisoa sa curl console kapa moreki oa Insomnia REST, kapa ka ho phatlalatsa API ho Rapid API.

Ho ngola API ho Python (ka Flask le RapidAPI)

Ho phatlalatsa API ea rona

RapidAPI ke 'maraka o moholo ka ho fetisisa lefatšeng o nang le li-API tse fetang 10 (le bahlahisi ba ka bang milione e le 'ngoe).

RapidAPI ha e fane feela ka sebopeho se le seng sa ho sebetsa le li-API tsa mokha oa boraro, empa hape e u lumella ho phatlalatsa API ea hau kapele le ha bonolo.

E le hore u ka etsa joalo, o lokela ho qala ka ho e phatlalatsa ho seva se seng marang-rang. Tabeng ea rona, re tla e sebelisa Heroku. Ho sebetsa le eena ha hoa lokela ho baka mathata, (u ka fumana ho eketsehileng ka eona mona).

Mokhoa oa ho phatlalatsa API ea hau ho Heroku

1. Kenya Heroku.

Mohato oa pele ke ho ngolisa le ho kenya Heroku Command Line Interface (CLI). Sena se sebetsa ho Ubuntu 16+.

sudo snap kenya heroku --classic

Ebe re kena:

ho kena ha heroku

2. Kenya lifaele tse hlokahalang.

Joale re hloka ho kenyelletsa lifaele tseo re lokelang ho li phatlalatsa ho foldareng ts'ebelisong ea rona:

  • ditlhoko.txt e nang le lenane la dimmojule tse hlokehang tsa Python;
  • Procfile, e hlalosang hore na ke litaelo life tse lokelang ho etsoa ho tsamaisa kopo;
  • .gitignore - ho qhelela ka thoko lifaele tse sa hlokahaleng ho seva.

Faele ya requirements.txt e tla ba le mela e latelang:

  • botlolo
  • e phomotsang
  • sethunya

Ka kopo hlokomela hore re kentse li-gunicorn (Python WSGI HTTP Server) lethathamong hobane re hloka ho tsamaisa kopo ea rona ho seva.

Profaele e tla ba le:

web: app ea gunicorn: app

Litaba tsa .gitignore:

*.pyc
__pycache__/

Kaha joale lifaele li se li entsoe, ha re qaleng git repo ebe re etsa:

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

3. Etsa sesebelisoa se secha sa Heroku.

heroku create

Ho sutumelletsa lekala le leholo ho Heroku repo e hole:

git push heroku master

Joale o ka qala ka ho bula Tšebeletso ea API ka litaelo:

heroku ps:scale web=1
heroku open
 

API e tla fumaneha ho your-random-heroku-name.herokuapp.com/ai-quotes.

Mokhoa oa ho kenyelletsa Python API ea hau 'marakeng oa RapidAPI

Hang ha tšebeletso ea API e hatisoa ho Heroku, u ka e kenya ho Rapid API. Mona litokomane tse qaqileng ka taba ena.

1. Etsa akhaonto ea RapidAPI.

Ho ngola API ho Python (ka Flask le RapidAPI)

Re ngolisa akhaonto ea mahala - sena se ka etsoa ho sebelisa Facebook, Google, GitHub.

Ho ngola API ho Python (ka Flask le RapidAPI)

2. Eketsa API ho phanele ea taolo.

Ho ngola API ho Python (ka Flask le RapidAPI)

3. E latelang, kenya lintlha tse akaretsang mabapi le API ea hau.

Ho ngola API ho Python (ka Flask le RapidAPI)

4. Ka mor'a ho tobetsa "Add API" leqephe le lecha le hlaha moo u ka kenyang boitsebiso ka API ea rona.

Ho ngola API ho Python (ka Flask le RapidAPI)

5. Hona joale u ka khona ho kena ka bowena API endpoints, kapa download faele ea swagger sebelisa OpenAPI.

Ho ngola API ho Python (ka Flask le RapidAPI)

Joale, joale o hloka ho beha lintlha tsa ho qetela tsa API ea rona leqepheng la Endpoints. Tabeng ea rona, lintlha tsa ho qetela li lumellana le mohopolo oa CRUD (fumana, poso, beha, hlakola).

Ho ngola API ho Python (ka Flask le RapidAPI)

Ka mor'a moo, o hloka ho theha ntlha ea ho qetela ea GET AI Quote e bonts'ang qotso e sa reroang (haeba ID e le ea kamehla) kapa qotsa bakeng sa ID e boletsoeng.

Ho theha ntlha ea ho qetela, o hloka ho tobetsa konopo ea "Create Endpoint".

Ho ngola API ho Python (ka Flask le RapidAPI)

Re pheta ts'ebetso ena bakeng sa lintlha tse ling kaofela tsa API. Ke phetho! Rea u lebohela, u phatlalalitse API ea hau!

Haeba tsohle li tsamaea hantle, leqephe la API le tla shebahala tjena:

Ho ngola API ho Python (ka Flask le RapidAPI)

fihlela qeto e

Sehloohong sena, re tsamaile ka mokhoa oa ho iketsetsa Tšebeletso ea RESTful API ho Python, hammoho le mokhoa oa ho phatlalatsa API ho leru la Heroku le ho e eketsa bukeng ea RapidAPI.

Empa phetolelong ea liteko, ho ile ha bontšoa feela melao-motheo ea motheo ea nts'etsopele ea API - li-nuances tse kang ts'ireletso, mamello ea liphoso le scalability ha lia ka tsa nkoa.

Ha ho etsoa API ea 'nete, sena sohle se tlameha ho tsotelloa.

Source: www.habr.com

Eketsa ka tlhaloso