fastApi Flashcards
virtual environments
py -m venv venv
venv/scripts/activate
pip install fastapi
pip install uvicorn
correr el servidor
reload: recargar la pagina
uvicorn main:app –reload –port 5000
open since other desvices
uvicorn main:app –reload –port 5000 –host 0.0.0.0
documentation Swagger
http://127.0.0.1:5000/docs
example basic
from fastapi import FastAPI
app = FastAPI()
@app.get(“/”)
def home():
return {“message”: “¡Hola Mundo!”}
change the name & vesion => of documentation in Swagger
app = FastAPI()
app.title = “My First FastAPI App”
app.version = “0.0.1”
TAGS => in documentation
@app.get(“/uno”, tags=[“home”])
get receive parameters :
localhost/movies/1
@app.get(‘/movies/{id}’, tags=[‘movies’])
@app.get(‘/movies/{id}’, tags=[‘movies’])
def get_movie22(id: int):
for movie in movies:
if id == movie[“id”]:
return movie
return
get receive parameters
localhost/movies/?category=Acccion&year=2000
@app.get(‘/movies/’, tags=[‘movies’])
def get_movies_by_category(category: str, year: int):
return [ item for item in movies if item[‘category’] == category ]
reply HTTP (replai)
HTMLResponse
from fastapi.responses import HTMLResponse
SCHEMA (eskima) => fill like a CLASS
from pydantic import BaseModel, Field
class Movie(BaseModel):
@app.post(‘/movies’, tags=[‘movies’])
def create_movie(movie: Movie):
movies.append(movie)
return movies
class Movie(BaseModel):
id: Optional[int] = None
title: str = Field(min_length=5, max_length=15)
overview: str = Field(min_length=15, max_length=50)
year: int = Field(le=2022)
rating:float = Field(ge=1, le=10)
category:str = Field(min_length=5, max_length=15)
class Config: schema_extra = { "example": { "id": 1, "title": "Mi película", "overview": "Descripción de la película", "year": 2022, "rating": 9.8, "category" : "Acción" } }
Query
from fastapi import FastAPI, Body, Path, Query
@app.get(‘/movies/’, tags=[‘movies’])
def get_movies_by_category(category: str = Query(min_length=5, max_length=15)):
Path
from fastapi import FastAPI, Body, Path, Query
@app.get(‘/movies/{id}’, tags=[‘movies’])
def get_movie(id: int = Path(ge=1, le=2000)):
for item in movies: if item["id"] == id: return item return []
status code
200 => Ok
201 => Created
400 => Bad request (request // solicitud)
401 => No authorized
Not authenticated
authorized (a-to-raizd)
403 => forbidden // token