25
loading...
This website collects cookies to deliver better user experience
FastAPI was introduced to the options for the first time with this iteration of the survey, and it appears to be the third most popular web framework for Python.
pip install fastapi[all]
uvicorn
sera installé en même temps. Il nous servira de serveur pour nos exemples.myapi
, on crée un fichier main.py
:from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "hello, world"}
FastAPI
nommée app
, puis on ajoute une route vers la racine avec une opération GET, grâce une élégante syntaxe à base d'annotations.$> cd myapi
$> uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [1972] using watchgod
INFO: Started server process [16100]
INFO: Waiting for application startup.
INFO: Application startup complete.
uvicorn
comme serveur. On lui demande d'utiliser le module Python main
(il faut donc exécuter la commande depuis le dossier où se trouve notre fichier main.py
) et y chercher l'instance app
de FastAPI.--reload
demande à uvicorn
de recharger le site au fur et à mesure que le fichier main.py
est modifié, sans avoir besoin de redémarrer l'application./about
dans à notre API :@app.get('/about')
async def about():
return {"about": "This is my first api with FastAPI"}
uvicorn
montrent que les changements sont bien détectés et chargés :WARNING: WatchGodReload detected file change in '['C:\\myapi\\main.py']'. Reloading...
INFO: Started server process [3708]
INFO: Waiting for application startup.
INFO: Application startup complete.
users
avec la liste des utilisateurs. On ajoute une route de type GET pour récupérer cette liste, et une route de type POST pour ajouter un élément à cette liste :users = ['pierre', 'natacha', 'benjamin']
@app.get('/users/list')
async def users_list():
"""Get the list of available users."""
return json.dumps(users)
@app.post('/users/add/{name}')
async def users_add(name: str):
"""Add a new user.
:param name: the name of the new user
"""
users.append(name)
return {'added': name}
curl
pour tester nos nouvelles routes :$ curl --request GET http://127.0.0.1:8000/users/list
"[\"pierre\", \"natacha\", \"benjamin\"]"
$ curl --request POST http://127.0.0.1:8000/users/add/florian
{"added":"florian"}
$ curl --request POST http://127.0.0.1:8000/users/add/denis
{"added":"denis"}
$ curl --request POST http://127.0.0.1:8000/users/add/bertrand
{"added":"bertrand"}
$ curl --request GET http://127.0.0.1:8000/users/list
"[\"pierre\", \"natacha\", \"benjamin\", \"florian\", \"denis\", \"bertrand\"]"
/openapi.json
:/docs
et /redoc
respectivement.uvicorn
remettra à jour /docs
et /redoc
pour qu'on puisse retester immédiatement.