Kulemba API mu Python (ndi Flask ndi RapidAPI)

Kulemba API mu Python (ndi Flask ndi RapidAPI)

Ngati mukuwerenga nkhaniyi, mwina mumadziwa kale zotheka zomwe zimatseguka mukamagwiritsa ntchito API (Chiyankhulo cha Mapulogalamu Ogwiritsa Ntchito).

Powonjezera imodzi mwama API ambiri agulu pa pulogalamu yanu, mutha kuwonjezera magwiridwe antchito a pulogalamuyi kapena kuwonjezera ndi data yofunikira. Koma bwanji ngati mwapanga chinthu chapadera chomwe mukufuna kugawana ndi anthu amdera lanu?

Yankho ndi losavuta: muyenera pangani API yanu.

Ngakhale izi zingawoneke ngati ntchito yovuta poyamba, ndizosavuta. Tikuwonetsani momwe mungachitire izi ndi Python.

Zomwe mukufunikira kuti muyambe

Kukula kwa API kumafuna:

  • Python3;
  • Botolo - chimango chosavuta komanso chosavuta kugwiritsa ntchito popanga mapulogalamu a pa intaneti;
  • Botolo-Wopuma ndikuwonjezera kwa Flask komwe kumakupatsani mwayi wopanga REST API mwachangu komanso ndikusintha kochepa.

Kukhazikitsa kumachitika ndi lamulo:

pip install flask-restful

Tikupangira pulogalamu yaulere yaulere kwa oyamba kumene:
Kukula kwa Telegraph bot mu C # - Ogasiti 26-28. Kuchuluka kwaulere komwe kumakupatsani mwayi womvetsetsa momwe othandizira bots amagwirira ntchito, mawonekedwe ogwirira ntchito ndi Telegraph API ndi zina zambiri. Otsatira atatu apamwamba adzalandira ma ruble 30 kuchokera ku Skillbox.

Musanayambe

Tipanga RESTful API yokhala ndi zoyambira CRUID ntchito.

Kuti timvetsetse bwino ntchitoyo, tiyeni timvetsetse mawu awiri omwe tatchulawa.

Kodi REST ndi chiyani?

REST API (Representational State Transfer) ndi API yomwe imagwiritsa ntchito zopempha za HTTP kusinthanitsa deta.

Ma REST API akuyenera kukwaniritsa zofunikira zina:

  • Zomangamanga za kasitomala: kasitomala amalumikizana ndi mawonekedwe ogwiritsira ntchito, ndipo seva imalumikizana ndi backend ndi sitolo ya data. Wothandizira ndi seva ndizodziyimira pawokha, aliyense wa iwo akhoza kusinthidwa mosiyana ndi ena.
  • Stateless - Palibe kasitomala yemwe wasungidwa pa seva. Gawo lachigawo limasungidwa kumbali ya kasitomala.
  • Cacheability - Makasitomala amatha kubisa mayankho a seva kuti apititse patsogolo magwiridwe antchito.

CRUD ndi chiyani?

CHIWALO ndi lingaliro la pulogalamu lomwe limafotokoza zinthu zinayi zofunika (kupanga, kuwerenga, kusintha ndi kufufuta).

Mu REST API, mitundu yofunsira ndi njira zofunsira ndizochita zinthu monga kutumiza, kupeza, kuyika, kufufuta.

Tsopano popeza tathana ndi mawu oyambira, titha kuyamba kupanga API.

Development

Tiyeni tipange mosungiramo mawu okhudza luntha lochita kupanga. AI ndi imodzi mwamaukadaulo omwe akukula mwachangu masiku ano, ndipo Python ndi chida chodziwika bwino chogwirira ntchito ndi AI.

Ndi API iyi, wopanga Python amatha kuphunzira mwachangu za AI ndikulimbikitsidwa ndi zatsopano zomwe zachitika. Ngati wopangayo ali ndi malingaliro ofunikira pamutuwu, azitha kuwawonjezera kunkhokwe.

Tiyeni tiyambe ndikulowetsamo ma module ofunikira ndikukhazikitsa Flask:

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

Muchidule ichi, Flask, Api ndi Resource ndi makalasi omwe timafunikira.

Reqparse ndi Flask-RESTful application parsing interface... Mudzafunikanso gawo losasinthika kuti muwonetse mawu osavuta.

Tsopano tipanga malo osungiramo mawu okhudza AI.

Kulowa kulikonse kwa repo kudzakhala ndi:

  • ID ya digito;
  • dzina la wolemba mawuwo;
  • mawu.

Popeza ichi ndi chitsanzo chophunzirira, tidzasunga zolemba zonse pamndandanda wa Python. Mu pulogalamu yeniyeni, titha kugwiritsa ntchito database m'malo mwake.

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

Tsopano tikufunika kupanga gulu lazinthu la Quote lomwe lidzafotokozere magwiridwe antchito a ma API athu. Njira zinayi ziyenera kulengezedwa mkati mwa kalasi: pezani, positi, ikani, chotsani.

Tiyeni tiyambe ndi njira ya GET

Zimakupatsani mwayi wopeza mawu enaake pofotokoza ID yake, kapena mawu osasintha ngati palibe ID yomwe yatchulidwa.

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

Njira ya GET imabweretsanso mawu osasinthika ngati ID ili ndi mtengo wokhazikika, i.e. ID sinakhazikitsidwe poyimba njira.

Ngati yakhazikitsidwa, ndiye njirayo imasaka pakati pa zolemba ndikupeza yomwe ili ndi ID yoperekedwa. Ngati palibe chomwe chapezeka, uthenga wakuti "Quote sunapezeke, 404" ukuwonetsedwa.

Kumbukirani, njirayo imabwezera HTTP 200 ngati pempho lidapambana ndipo 404 ngati kulowa sikunapezeke.

Tsopano tiyeni tipange njira ya POST kuti muwonjezere mawu atsopano kumalo osungira

Ipeza id ya mawu atsopano aliwonse pamene mukulemba. Kuphatikiza apo, POST idzagwiritsa ntchito reqparse kusanthula magawo omwe azipita muzopempha (wolemba ndi mawu obwereza).

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

Mu code pamwambapa, njira ya POST idavomereza ID yamtengo. Kenako, pogwiritsa ntchito reqparse, idatenganso wolembayo ndikulemba mawu kuchokera pa pempho, kuwasunga mu dikishonale ya params.

Ngati mawu omwe ali ndi ID yotchulidwa alipo kale, ndiye kuti njirayo ikuwonetsa uthenga woyenera ndi nambala 400.

Ngati mawu omwe ali ndi chidziwitso chodziwika sichinapangidwe, njirayo imapanga cholowa chatsopano ndi ID ndi wolemba, komanso magawo ena. Imawonjezera cholowera pamndandanda wa ai_quotes ndikubwezeretsa cholowa ndi mawu atsopano pamodzi ndi 201 code.

Tsopano tikupanga njira ya PUT yosinthira mawu omwe alipo m'malo osungira

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

Njira ya PUT, yofanana ndi chitsanzo cham'mbuyomu, imatenga chizindikiritso ndi cholowetsa ndikuyika magawo atchuthi pogwiritsa ntchito reqparse.

Ngati mawu omwe ali ndi ID yotchulidwa alipo, njirayo idzasinthidwa ndi magawo atsopano ndikutulutsa mawu osinthidwa ndi code 200. Ngati palibe mawu omwe ali ndi ID yotchulidwa pano, mbiri yatsopano yokhala ndi code 201 idzapangidwa.

Pomaliza, tiyeni tipange DELETE njira yochotsera mawu omwe salinso olimbikitsa.

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

Njirayi imatenga ID yachidziwitso ngati cholowetsa ndikusintha mndandanda wa ai_quotes pogwiritsa ntchito mndandanda womwe wagawidwa.

Tsopano popeza tapanga njira zonse, zomwe tikuyenera kuchita ndikungowonjezera zothandizira ku API, kukhazikitsa njira, ndikuyendetsa Flask.

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

Ntchito yathu ya REST API yakonzeka!

Kenako, titha kusunga kachidindo ku fayilo ya app.py poyiyendetsa mu console ndi lamulo:

python3 app.py

Ngati zonse zili bwino, ndiye kuti tipeza zinthu monga izi:

* Debug mode: Yayatsidwa
* Kuthamanga 127.0.0.1:5000/ (Dinani CTRL+C kuti musiye)
* Kuyambiranso ndi stat
* Debugger ikugwira ntchito!
* PIN ya Debugger: XXXXXXX

Kuyesa API

API ikapangidwa, iyenera kuyesedwa.

Izi zitha kuchitika pogwiritsa ntchito pulogalamu ya curl console kapena kasitomala wa Insomnia REST, kapena pofalitsa API pa Rapid API.

Kulemba API mu Python (ndi Flask ndi RapidAPI)

Kusindikiza API yathu

RapidAPI ndiye msika waukulu kwambiri padziko lonse lapansi wokhala ndi ma API opitilira 10 (komanso opanga 000 miliyoni).

RapidAPI sikuti imangopereka mawonekedwe amodzi ogwirira ntchito ndi ma API a chipani chachitatu, komanso imakupatsani mwayi wofalitsa API yanu mwachangu komanso mosavuta.

Kuti chitani izo, choyamba muyenera kuzisindikiza ku seva ina pa intaneti. M'malo mwathu, tidzagwiritsa ntchito Heroku. Kugwira naye ntchito sikuyenera kuyambitsa zovuta, (mutha kudziwa zambiri za izi pano).

Momwe mungasinthire API yanu pa Heroku

1. Ikani Heroku.

Gawo loyamba ndikulembetsa ndikuyika Heroku Command Line Interface (CLI). Izi zimagwira ntchito pa Ubuntu 16+.

sudo snap kukhazikitsa heroku --classic

Kenako timalowa:

heroku login

2. Onjezani mafayilo ofunikira.

Tsopano tikufunika kuwonjezera mafayilo oti tifalitse ku chikwatu mu pulogalamu yathu:

  • zofunikira.txt ndi mndandanda wa ma module a Python;
  • Procfile, yomwe imatchula malamulo omwe ayenera kuchitidwa kuti agwiritse ntchito;
  • .gitignore - kuchotsa mafayilo omwe safunikira pa seva.

Fayilo ya requirements.txt idzakhala ndi mizere iyi:

  • botolo
  • botolo-yopuma
  • mfuti

Chonde dziwani kuti tawonjezera gunicorn (Python WSGI HTTP Server) pamndandanda chifukwa tikuyenera kuyendetsa pulogalamu yathu pa seva.

Mbiri idzakhala ndi:

ukonde: pulogalamu ya gunicorn: app

Zomwe zili mu .gitignore:

*.pyc
__pycache__/

Tsopano mafayilo apangidwa, tiyeni tiyambitse git repo ndikudzipereka:

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

3. Pangani pulogalamu yatsopano ya Heroku.

heroku create

Kukankhira master nthambi ku Heroku repo yakutali:

git push heroku master

Tsopano mutha kuyamba ndikutsegula API Service ndi malamulo:

heroku ps:scale web=1
heroku open
 

API ipezeka pa your-random-heroku-name.herokuapp.com/ai-quotes.

Momwe mungawonjezere Python API yanu pamsika wa RapidAPI

Ntchito ya API ikasindikizidwa pa Heroku, mutha kuwonjezera ku Rapid API. Pano zolembedwa mwatsatanetsatane pamutuwu.

1. Pangani akaunti ya RapidAPI.

Kulemba API mu Python (ndi Flask ndi RapidAPI)

Timalembetsa akaunti yaulere - izi zitha kuchitika pogwiritsa ntchito Facebook, Google, GitHub.

Kulemba API mu Python (ndi Flask ndi RapidAPI)

2. Onjezani API ku gulu lolamulira.

Kulemba API mu Python (ndi Flask ndi RapidAPI)

3. Kenako, lowetsani zambiri za API yanu.

Kulemba API mu Python (ndi Flask ndi RapidAPI)

4. Mukadina "Add API" tsamba latsopano likuwonekera pomwe mungalowetse zambiri za API yathu.

Kulemba API mu Python (ndi Flask ndi RapidAPI)

5. Tsopano inu mukhoza mwina pamanja kulowa API endpoints, kapena kukopera fayilo ya swagger pogwiritsa ntchito OpenAPI.

Kulemba API mu Python (ndi Flask ndi RapidAPI)

Chabwino, tsopano muyenera kukhazikitsa mathero a API yathu patsamba la Endpoints. Kwa ife, mapeto amafanana ndi lingaliro la CRUD (tenga, kutumiza, kuika, kuchotsa).

Kulemba API mu Python (ndi Flask ndi RapidAPI)

Kenako, muyenera kupanga GET AI Quote endpoint yomwe imawonetsa mawu osasintha (ngati ID ndi yokhazikika) kapena mawu a ID yotchulidwa.

Kuti mupange mapeto, muyenera dinani batani la "Pangani Endpoint".

Kulemba API mu Python (ndi Flask ndi RapidAPI)

Timabwereza ndondomekoyi kwa ma API ena onse. Ndizomwezo! Zabwino zonse, mwasindikiza API yanu!

Zonse zikayenda bwino, tsamba la API liziwoneka motere:

Kulemba API mu Python (ndi Flask ndi RapidAPI)

Pomaliza

M'nkhaniyi, tinadutsa njira yopangira RESTful API Service ku Python, pamodzi ndi ndondomeko yosindikiza API ku mtambo wa Heroku ndikuwonjezera ku RapidAPI directory.

Koma mu mtundu woyeserera, mfundo zoyambira zokha za chitukuko cha API zidawonetsedwa - ma nuances monga chitetezo, kulolerana zolakwa ndi scalability sanaganizidwe.

Popanga API yeniyeni, zonsezi ziyenera kuganiziridwa.

Source: www.habr.com

Kuwonjezera ndemanga