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.
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.
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.
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
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.
* 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.
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;
4. Mukadina "Add API" tsamba latsopano likuwonekera pomwe mungalowetse zambiri za API yathu.
5. Tsopano inu mukhoza mwina pamanja kulowa API endpoints, kapena kukopera fayilo ya swagger pogwiritsa ntchito OpenAPI.
Chabwino, tsopano muyenera kukhazikitsa mathero a API yathu patsamba la Endpoints. Kwa ife, mapeto amafanana ndi lingaliro la CRUD (tenga, kutumiza, kuika, kuchotsa).
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".
Timabwereza ndondomekoyi kwa ma API ena onse. Ndizomwezo! Zabwino zonse, mwasindikiza API yanu!
Zonse zikayenda bwino, tsamba la API liziwoneka motere:
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.