Si w ap li atik sa a, pwobableman ou deja abitye ak posiblite ki vini ak lè l sèvi avèk yon API (Application Programming Interface).
Lè w ajoute youn nan anpil API ki louvri nan aplikasyon w lan, ou ka pwolonje fonksyonalite aplikasyon an oswa anrichi li ak done ki nesesè yo. Men, e si ou devlope yon karakteristik inik ke ou vle pataje ak kominote a?
Repons lan se senp: ou bezwen kreye pwòp API ou.
Malgre ke sa a ka sanble tankou yon travay difisil nan premye, li se aktyèlman senp. Nou pral montre w kouman fè sa lè l sèvi avèk Python.
Sa ou bezwen pou kòmanse
Pou devlope yon API ou bezwen:
Python3;
Flask — yon kad ki senp epi fasil pou itilize pou kreye aplikasyon entènèt;
Flacon-RESTful se yon ekstansyon pou Flask ki pèmèt ou devlope yon API REST rapidman ak konfigirasyon minim.
Enstalasyon fèt ak kòmandman an:
pip install flask-restful
Nou rekòmande yon kou pwogramasyon entansif gratis pou débutan: Devlopman telegram bot nan C# — 26–28 out. Yon kou entansif gratis ki pèmèt ou konprann ki jan asistan bots travay, spesifik yo nan travay ak API a Telegram ak lòt nuans. Twa pi bon patisipan yo pral resevwa 30 rubles nan Skillbox.
Pou byen konprann travay la, ann konprann de tèm ki mansyone pi wo a.
ki sa ki REST?
REST API (Representational State Transfer) se yon API ki itilize demann HTTP pou fè echanj done.
API REST dwe satisfè sèten kritè:
Achitekti kliyan-sèvè: Kliyan an reyaji avèk koòdone itilizatè a, epi sèvè a reyaji avèk backend la ak depo done. Kliyan an ak sèvè yo endepandan, nenpòt nan yo ka ranplase separeman de lòt la.
Apatrid - pa gen okenn done kliyan ki estoke sou sèvè a. Eta sesyon an estoke sou bò kliyan an.
Cacheability - Kliyan yo ka kache repons sèvè pou amelyore pèfòmans jeneral.
ki sa ki CRUD?
RAW se yon konsèp pwogramasyon ki dekri kat aksyon debaz (kreye, li, mete ajou ak efase).
Nan REST API, kalite demann ak metòd demann yo responsab pou aksyon tankou poste, jwenn, mete, efase.
Kounye a ke nou konprann tèm debaz yo, nou ka kòmanse kreye API a.
Devlopman
Ann kreye yon depo sitasyon sou entèlijans atifisyèl. AI se youn nan teknoloji k ap grandi pi rapid jodi a, ak Python se yon zouti popilè pou travay ak AI.
Avèk API sa a, yon pwomotè Python ka byen vit jwenn enfòmasyon sou AI epi jwenn enspire pa nouvo pwogrè. Si yon pwomotè gen panse ki gen anpil valè sou sijè sa a, li pral kapab ajoute yo nan repozitwa a.
Ann kòmanse pa enpòte modil ki nesesè yo epi mete kanpe Flask:
from flask import Flask
from flask_restful import Api, Resource, reqparse
import random
app = Flask(__name__)
api = Api(app)
Nan snippet sa a, Flask, Api ak Resous se klas nou bezwen yo.
Reqparse se yon koòdone analize rechèch Flask-RESTful... Ou pral bezwen tou yon modil o aza pou montre yon quote o aza.
Koulye a, nou pral kreye yon depo sitasyon sou AI.
Chak antre repo pral genyen:
ID dijital;
non otè sitasyon an;
quote.
Depi sa a se jis yon egzanp fòmasyon, nou pral estoke tout antre nan yon lis Python. Nan yon aplikasyon reyèl, nou ta gen anpil chans itilize yon baz done olye.
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."
}
]
Koulye a, nou bezwen kreye yon klas resous Quote ki pral defini operasyon yo nan pwen final API nou an. Anndan klas la ou bezwen deklare kat metòd: jwenn, poste, mete, efase.
Ann kòmanse ak metòd GET
Li fè li posib pou jwenn yon quote espesifik lè yo espesifye ID li yo, oswa yon quote o aza si ID la pa espesifye.
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
Metòd GET a retounen yon quote o aza si ID la gen valè default la, i.e. pa gen okenn ID espesifye lè w ap rele metòd la.
Si li espesifye, Lè sa a, metòd la rechèch pami sitasyon yo epi li jwenn youn nan ki gen ID espesifye a. Si pa jwenn anyen, mesaj "Pa jwenn quote, 404" parèt.
Sonje byen: metòd la retounen yon estati HTTP nan 200 si demann lan te reyisi ak 404 si dosye a pa te jwenn.
Koulye a, ann kreye yon metòd POST pou ajoute yon nouvo quote nan depo a
Li pral jwenn ID chak nouvo quote pandan w ap tape. Anplis de sa, POST pral sèvi ak reqparse analize paramèt yo ki pral ale nan kò demann lan (otè ak quote tèks).
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
Nan kòd ki pi wo a, metòd POST la aksepte ID quote la. Lè sa a, lè l sèvi avèk reqparse, li rekipere otè a ak sitasyon nan rechèch la, estoke yo nan diksyonè a params.
Si yon quote ak ID espesifye deja egziste, metòd la montre yon mesaj korespondan ak kòd 400.
Si yon sitasyon ki gen ID espesifye a poko te kreye, metòd la kreye yon nouvo dosye ak ID espesifye a ak otè, osi byen ke lòt paramèt. Lè sa a, li ajoute antre nan lis la ai_quotes epi retounen antre a ak nouvo quote la ansanm ak yon kòd 201.
Koulye a, nou kreye yon metòd PUT pou chanje yon quote ki deja egziste nan depo a
Metòd PUT, menm jan ak egzanp anvan an, pran ID ak opinyon epi analize paramèt quote yo lè l sèvi avèk reqparse.
Si yon sitasyon ki gen ID espesifye a egziste, metòd la pral mete ajou li ak nouvo paramèt yo epi answit bay sitasyon ki ajou ak kòd 200. Si pa gen okenn sitasyon ak ID espesifye a ankò, yon nouvo dosye ak kòd 201 pral kreye.
Finalman, ann kreye yon metòd DELETE pou retire yon quote ki pa enspire ankò
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
Metòd sa a jwenn idantite quote la kòm opinyon epi mete ajou lis ai_quotes la lè l sèvi avèk lis pataje a.
Kounye a ke nou te kreye tout metòd yo, tout sa nou bezwen fè se tou senpleman ajoute yon resous nan API a, mete chemen an, epi kouri Flask.
api.add_resource(Quote, "/ai-quotes", "/ai-quotes/", "/ai-quotes/<int:id>")
if __name__ == '__main__':
app.run(debug=True)
Sèvis REST API nou an pare!
Apre sa, nou ka sove kòd la nan fichye app.py a pa kouri li nan konsole a lè l sèvi avèk lòd la:
python3 app.py
Si tout bagay bon, Lè sa a, nou pral jwenn yon bagay tankou sa a:
* Debug mòd: sou
*Kouri sou 127.0.0.1:5000/ (Peze CTRL + C pou kite)
* Rekòmanse ak stat
* Debugger aktif!
* PIN debogaj: XXXXXXX
Tès API a
Yon fwa yo kreye API a, li bezwen teste.
Sa a ka fè lè l sèvi avèk sèvis piblik Curl konsole a oswa kliyan an REST Insomnia, oswa pa pibliye API a sou Rapid API.
Pibliye API nou an
RapidAPI se pi gwo mache nan mond lan ak plis pase 10 API (ak apeprè 000 milyon devlopè).
RapidAPI pa sèlman bay yon sèl koòdone pou travay ak API twazyèm pati, men tou li ba ou kapasite pou pibliye pwòp API ou byen vit ak fasil.
Ki jan yo ajoute API Python ou a sou mache RapidAPI a
Yon fwa yo pibliye sèvis API ou sou Heroku, ou ka ajoute li nan API Rapid la. Isit la dokiman detaye sou sijè sa a.
1. Kreye yon kont RapidAPI.
Enskri yon kont gratis - sa a ka fè lè l sèvi avèk Facebook, Google, GitHub.
2. Ajoute API a nan panèl kontwòl la.
3. Apre sa, antre enfòmasyon jeneral sou API ou.
4. Apre klike "Ajoute API" yon nouvo paj parèt kote ou ka antre enfòmasyon sou API nou an.
5. Koulye a, ou ka swa manyèlman antre nan pwen final API yo oswa telechaje swagger-dosye lè l sèvi avèk OpenAPI.
Oke, kounye a nou bezwen mete pwen final yo nan API nou an sou paj la Endpoints. Nan ka nou an, pwen final yo koresponn ak konsèp CRUD (jwenn, poste, mete, efase).
Apre sa, ou bezwen kreye yon pwen final GET AI Quote ki montre yon quote o aza (si ID la se default) oswa yon quote pou ID espesifye a.
Pou kreye yon pwen final, klike sou bouton "Kreye pwen final".
Nou repete pwosesis sa a pou tout lòt pwen final API. Se tout! Felisitasyon, ou pibliye API ou a!
Si tout bagay byen, paj API a pral gade yon bagay tankou sa a:
Konklizyon
Nan atik sa a, nou te aprann pwosesis pou kreye pwòp sèvis API RESTful ou nan Python, ansanm ak pwosesis pou pibliye API nan nwaj Heroku a epi ajoute li nan anyè RapidAPI.
Men, vèsyon tès la te montre sèlman prensip debaz yo nan devlopman API - nuans tankou sekirite, tolerans fay ak évolutivité pa te konsidere.
Lè w ap devlope yon API reyèl, tout bagay sa yo dwe pran an kont.