Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Creando ejemplos de Path y Query parameters automáticos

19/20
Recursos

Aportes 6

Preguntas 2

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

Código completo funcionando hasta esta clase

# Python
from typing import Optional
from enum import Enum

# Pydantic
from pydantic import BaseModel
from pydantic import Field

# FastAPI
from fastapi import FastAPI
from fastapi import Body, Query, Path

app = FastAPI()

# Models

class HairColor(Enum):
    white = "white"
    brown = "brown"
    black = "black"
    blonde = "blonde"
    red = "red"

class Location(BaseModel):
    city: str = Field(
        ...,
        min_length=1,
        max_length=50,
        description="The city where the person lives",
        example="New York",
    )
    state: str = Field(
        ...,
        min_length=1,
        max_length=50,
        description="The state where the person lives",
        example="New York",
    )
    country: str = Field(
        ...,
        min_length=1,
        max_length=50,
        description="The country where the person lives",
        example="United States",
    )

class Person(BaseModel):
    first_name: str = Field(
        ...,
        min_length=1,
        max_length=50,
        example="Miguel"
        )
    last_name: str = Field(
        ...,
        min_length=1,
        max_length=50,
        example="Gonzalez"
        )
    age: int = Field(
        ...,
        gt=0,
        le=115,
        example=25
    )
    hair_color: Optional[HairColor  ] = Field(default=None, example=HairColor.brown)
    is_married: Optional[bool] = Field(default=None, example=False)

    #class Config:
    #    schema_extra = {
    #        "example": {
    #            "first_name": "Facundo",
    #            "last_name": "García Martoni",
    #            "age": 29,
    #            "hair_color": "blonde",
    #            "is_married": False,
    #        }
    #    }

@app.get("/")
def home():
    return {"Hello": "World!"}

# Request and Response Body

@app.post("/person/new")
def create_person(person: Person = Body(...)):
    return person

# Validaciones: Query Parameters

@app.get("/person/detail")
def show_person(
    name: Optional[str] = Query(
        None, min_length=1,
        max_length=50,
        title="Person Name",
        description="This is the person name,  It's between 1 and 50 characters",
        example="Rocio"
        ),
    age: str = Query(
        ...,
        title="Person Age",
        description="This is the person age, It's required",
        example="25"
        )
):
    return {name: age}

# Validaciones Path Paremeters

@app.get("/person/detail/{person_id}")
def show_person(
    person_id: int = Path(
        ...,
        gt=0,
        example=123
    )
):
    return {person_id: "It exists!"}

# Validaciones: Request Body

@app.put("/person/{person_id}")
def update_person(
    person_id: int = Path(
        ...,
        title="Person ID",
        description="This is the person ID",
        gt=0,
        example=123
    ),
    person: Person = Body(...),
    location: Location = Body(...)
):
    #results = person.dict()
    #results.update(location.dict())
    #return results
    return person

en vez de hacer git add se puede hacer directamente

git commit -am "mesagge"

hacer muchos ejercicios

Para Path y Query parameters se pueden crear ejemplos automáticos de la misma manera que se hizo con Request body, es decir, usando la palabra example en la path operation function.

# Validaciones: Query Parameters
@app.get('/person/detail')
def show_person(
    name: Optional[str] = Query(
        None,
        min_length=1,
        max_length=50,
        title='Person name',
        description='This is the person name. It is between 1 and 50 characters',
        example='Dulce'
        ),
    age: str = Query(
        ...,
        title='Person age',
        description='This is the person age. It is required',
        example=22
        )
):
    return {name: age}

# Validaciones: Path Parameters
@app.get('/person/detail/{person_id}')
def show_person(
    person_id: int = Path(
        ...,
        gt=0,
        title='Person ID',
        description='This is the person ID. It is required',
        example=30
        )
):
    return {person_id: 'It exists!'}

# Validaciones: Request Body
@app.put('/person/{person_id}')
def update_person(
    person_id: int = Path(
        ...,
        title='Person ID',
        description='This is the person ID. It is required',
        gt=0,
        example=32
    ),
    person: Person = Body(...),
    location: Location = Body(...)
):
    results = person.dict()
    results.update(location.dict())
    return results

Sigo muy motivado a avanzar en este curso:

#Python
from typing import Optional
from fastapi.params import Path
from enum import Enum

#Pydantic
from pydantic import BaseModel
from pydantic import Field
from pydantic import EmailStr, HttpUrl, PaymentCardNumber

# FastAPI
from fastapi import FastAPI
from fastapi import Body, Query, Path
from pydantic.main import SchemaExtraCallable

app = FastAPI()

# Models

class HairColor(Enum):
    white = 'white'
    black = 'black'
    blonde = 'blonde'
    brown = 'brown'
    red = 'red'

class Location(BaseModel):
    city: str = Field(
        ...,
        min_length=4,
        max_length=24,
        example="Montevideo"
        )
    state: str = Field(
        ...,
        min_length=4,
        max_length=24,
        example="Montevideo"
        )
    country: str = Field(
        ...,
        min_length=4,
        max_length=24,
        example="Uruguay"
        )
    latam: bool = Field(example=True)
    # class Config_loc:
    #     schema_example={
    #         "example": {
    #             "city": "Montevideo",
    #             "state": "Montevideo",
    #             "country": "Uruguay",
    #             "latam": True
    #         }
    #     }

class Person(BaseModel): # Person parameters
    first_name: str = Field(
        ...,
        min_length=3,
        max_length=35,
        example="Tony"
        )
    last_name: str = Field(
        ...,
        min_length=3,
        max_length=35,
        example="Demarkovich"
        )
    age_person: int = Field(
        ...,
        ge=18,
        le=115,
        example=39
        )
    color_hair: Optional[HairColor] = Field(default=None, example=HairColor.black)
    married: Optional[bool] = Field(default=None, example=True)
    email_usr : EmailStr = Field(default=None, example="[email protected]")
    web_usr : HttpUrl = Field(default=None, example="***")
    pay_card_usr: PaymentCardNumber = Field(default=None, example="5158459994949763")

    # class Config:
    #     schema_extra = {
    #         "example": {
    #             "first_name": "Facundo",
    #             "last_name": "Garcia",
    #             "age_person": 39,
    #             "color_hair": "red",
    #             "married": True,
    #             "email_usr": "[email protected]",
    #             "web_usr": "***",
    #             "pay_card_usr": "5158459994949763"
    #         }
    #     }

@app.get("/") #Path operation decorator
def home(): #Path operation function
    return {"First API": "Congratulation"} #JSON

# Request and Response Bondy

@app.post("/person/new") # Acces a new person
def create_person(person: Person = Body(...)): # acces to the parameters of person
    return person

# Validations: Query Parameters

@app.get("/person/detail")
def show_person(
    name: Optional[str] = Query(
        None, 
        min_length=3, 
        max_length=35,
        title="Person Name",
        description="This is the person name. It's between 3 and 35 characters.",
        example="Pedro"
        ),
    age: str = Query(
        ...,
        title="Person Age",
        description="This is the person age. It's required.",
        example="34"
        )
):
    return {name: age}

# Validations: Path Parameters
@app.get("/person/detail/{person_id}")
def show_person(
    person_id: int = Path(
        ..., 
        gt=0,
        title="Person ID",
        description="This is the person ID. It's reqiuired and it's more than 0.",
        example=300
        )
):
    return {person_id: "it_exist!"}

# Validations: Request Body
@app.put("/person/{person_id}")
def update_person(
    person_id: int = Path(
        ...,
        title="Person ID",
        description="This is the person ID",
        gt=0,
        example=300
    ),
    person: Person = Body(...),
    location: Location = Body(...)
):
    results = person.dict()
    results.update(location.dict())
    return results 

Automatic path and query examples:
- Definimos con un valor la propiedad example en el tipo path ó query del parámetro definido en la path operation function