No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

Esqueleto de las Path Operations: Users

18/25
Recursos

Aportes 11

Preguntas 4

Ordenar por:

Los aportes, preguntas y respuestas son vitales para aprender en comunidad. Reg铆strate o inicia sesi贸n para participar.

Aporte

Si algui茅n est谩 siguiendo la recomendaci贸n que hice en este comentario les dejo la estructura en c贸digo.

C贸digo

# Python
from uuid import UUID
from datetime import date
from datetime import datetime
from typing import Dict
from typing import List
from typing import Optional

# Pydantic
from pydantic import BaseModel
from pydantic import EmailStr
from pydantic import Field

# FastAPI
from fastapi import FastAPI
from fastapi import status
from fastapi import Path


# Initialize the app
app = FastAPI()


# ============================================================
# Define models
# ============================================================

class UserBase(BaseModel):

    id: UUID = Field(...,)

    email: EmailStr = Field(...,)


class User(UserBase):

    first_name: str = Field(...,
                            title='First name',
                            min_length=2,
                            max_length=50,
                            example='John',)

    last_name: str = Field(...,
                           title='Last name',
                           min_length=2,
                           max_length=50,
                           example='Doe',)

    birth_date: Optional[date] = Field(default=None,
                                       title='Birth date',
                                       example='2021-01-01',)


class UserLogin(UserBase):

    password: str = Field(...,
                          min_length=8,
                          max_length=64,
                          example='password',)


class Tweet(BaseModel):

    id: UUID = Field(...)

    content: str = Field(...,
                         min_length=1,
                         max_length=256,)

    created_at: datetime = Field(default=datetime.now(),
                                title='Creation date',
                                example='2020-01-01T00:00:00Z',)

    updated_at: Optional[datetime] = Field(default=None,
                                           title='Last update date',
                                           example='2020-01-01T00:00:00Z',)

    created_by: User = Field(...,
                             title='User who created the tweet',)


# ============================================================
# Path operations
# ============================================================


@app.get('/',
         summary='Home',
         status_code=status.HTTP_200_OK)
def home() -> Dict[str, str]:
    """Home route.

    Returns a message indicating that the app is running.
    """

    return {
        'message': 'Twitter API is working!',
    }


## Auth
@app.post('/auth/signup',
          response_model=UserLogin,
          status_code=status.HTTP_201_CREATED,
          summary='Sign up',
          tags=['Auth', 'Users'])
def signup(user: User) -> User:
    pass


@app.post('/auth/login',
          response_model=UserLogin,
          status_code=status.HTTP_200_OK,
          summary='Login',
          tags=['Auth', 'Users'])
def login(user: User) -> User:
    pass


## Users


@app.get('/users/',
         response_model=List[User],
         status_code=status.HTTP_200_OK,
         summary='Get all users',
         tags=['Users'])
def list_users() -> List[User]:
    pass


@app.get('/users/{id}',
         response_model=User,
         status_code=status.HTTP_200_OK,
         summary='Get a user',
         tags=['Users'])
def retrieve_user(
    id: int = Path(...,
                   gt=0,
                   title='User ID',
                   description='The ID of the user to retrieve',
                   example=1,),
) -> User:
    pass


@app.put('/users/{id}',
         response_model=User,
         status_code=status.HTTP_200_OK,
         summary='Update user',
         tags=['Users'])
def update_user(
    id: int = Path(...,
                   gt=0,
                   title='User ID',
                   description='The ID of the user to update',
                   example=1,),
) -> User:
    pass


@app.delete('/users/{id}',
            status_code=status.HTTP_204_NO_CONTENT,
            summary='Delete user',
            tags=['Users'])
def delete_user(
    id: int = Path(...,
                   gt=0,
                   title='User ID',
                   description='The ID of the user to update',
                   example=1,),
) -> User:
    pass


## Tweets


@app.get('/tweets/',
         response_model=List[Tweet],
         status_code=status.HTTP_200_OK,
         summary='Get all tweets',
         tags=['Tweets'])
def list_tweets() -> List[Tweet]:
    pass


@app.get('/tweets/{id}',
         response_model=Tweet,
         status_code=status.HTTP_200_OK,
         summary='Get a tweet',
         tags=['Tweets'])
def retrieve_tweet(
    id: int = Path(...,
                   gt=0,
                   title='Tweet ID',
                   description='The ID of the tweet to retrieve',
                   example=1,),
) -> Tweet:
    pass


@app.put('/tweets/{id}',
         response_model=Tweet,
         status_code=status.HTTP_200_OK,
         summary='Update tweet',
         tags=['Tweets'])
def update_tweet(
    id: int = Path(...,
                   gt=0,
                   title='Tweet ID',
                   description='The ID of the tweet to update',
                   example=1,),
) -> Tweet:
    pass


@app.delete('/tweets/{id}',
            status_code=status.HTTP_204_NO_CONTENT,
            summary='Delete tweet',
            tags=['Tweets'])
def delete_tweet(
    id: int = Path(...,
                   gt=0,
                   title='Tweet ID',
                   description='The ID of the tweet to update',
                   example=1,),
) -> Tweet:
    pass

Repositorio remoto: GitHub

As铆 vamos here:

# Python
from uuid import UUID
from datetime import date
from datetime import datetime
from typing import Optional, List

# Pydantic
from pydantic import BaseModel
from pydantic import EmailStr
from pydantic import Field

# FastAPI
from fastapi import FastAPI
from fastapi import status

app = FastAPI()

# Models

class UserBase(BaseModel):
    user_id: UUID = Field(...)
    email: EmailStr = Field(...)

class UserLogin(UserBase):
    password: str = Field(
        ..., 
        min_length=8,
        max_length=64
    )

class User(UserBase):
    first_name: str = Field(
        ...,
        min_length=1,
        max_length=50
    )
    last_name: str = Field(
        ...,
        min_length=1,
        max_length=50
    )
    birth_date: Optional[date] = Field(default=None)

class Tweet(BaseModel):
    tweet_id: UUID = Field(...)
    content: str = Field(
        ..., 
        min_length=1, 
        max_length=256
    )
    created_at: datetime = Field(default=datetime.now())
    update_at: Optional[datetime] = Field(default=None)
    by: User = Field(...)

# Path Operations

@app.get(path="/")
def home():
    return {"Twitter API": "Working!"}

## Users

@app.post(
    path="/signup",
    response_model=User,
    status_code=status.HTTP_201_CREATED,
    summary="Register a User",
    tags=["Users"]
)
def signup(): 
    pass

@app.post(
    path="/login",
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary="Login a User",
    tags=["Users"]
)
def login(): 
    pass

@app.get(
    path="/users",
    response_model=List[User],
    status_code=status.HTTP_200_OK,
    summary="Show all users",
    tags=["Users"]
)
def show_all_users(): 
    pass

@app.get(
    path="/users/{user_id}",
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary="Show a User",
    tags=["Users"]
)
def show_a_user(): 
    pass

@app.delete(
    path="/users/{user_id}/delete",
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary="Delete a User",
    tags=["Users"]
)
def delete_a_user(): 
    pass

@app.put(
    path="/users/{user_id}/update",
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary="Update a User",
    tags=["Users"]
)
def update_a_user(): 
    pass


## Tweets

Para que mejores tu codigo, de una forma mas profesional鈥 Puedes hacer todo el import que necesites en una misma linea. no 4 lineas llamando al mismo metodo鈥 Ejemplo:

from pydantic import BaseModel, Field, EmailStr

Tambien puedes crear un archivo extra y llamarlo Models, y desde ahi crear tus modelos y luego llamarlos en tu main鈥 Ejemplo:

from models import UserBase, UserLogin, User, Tweet

y luego si declararlos en tus path鈥

Tambien puedes usar algo llamado Routes鈥 para tener archivos solo con las rutas especificas y que tu codigo no sea un spaguetti lleno de muchas cosas. A la final esto te permite estructurarte mejor y de una vez ir agarrando no solo buenas practicas. Si no, Practicas Profesionales.

Me parece que List de typing no es necesario apartar de la v3.9, se puede usar list, sin importar. Seria interesante que le echen un vistazo a la documentaci贸n.

Ayuda mucho este tipo de tests:

genial, se ve tan r谩pido todo ajajaj

Creo que el profe no lo menciona para no confundir, pero es posible llamar al mismo endpoint con los diferentes m茅todos HTTP, sin tener la necesidad de agregar un /update, /delete, etc. al final del path

@router.get(
    path="/{user_id}",
    response_model=User,
    summary="Shows a user based on the id",
)
def show_user():
    pass


@router.delete(
    path="/{user_id}",
    response_model=User,
    summary="Deletes a user based on the id",
)
def delete_user():
    pass


@router.put(
    path="/{user_id}",
    response_model=User,
    summary="Updates a user based on the id",
)
def update_user():
    pass

Tambi茅n notar谩n que estoy usando @router en lugar de @app, para no tener todos los endpoint en un solo archivo pueden usar la clase APIRouter como en el siguiente tutorial: https://www.fastapitutorial.com/blog/fastapi-route/, yo lo implemente de la siguiente manera

# main.py

from fastapi import FastAPI

from routes import route_auth, route_users

app = FastAPI()


@app.get(path="/")
def home():
    return {"Twitter API": "Working!"}


app.include_router(route_auth.router, prefix="/auth", tags=["Auth"])
app.include_router(route_users.router, prefix="/users", tags=["Users"])


# routes/route_auth.py

from fastapi import APIRouter, status

from models.user import User

router = APIRouter()


@router.post(
    path="/signup",
    response_model=User,
    status_code=status.HTTP_201_CREATED,
    summary="Register a new User",
)
def signup():
    pass


@router.post(
    path="/login",
    response_model=User,
    summary="Login a User",
)
def login():
    pass

Hay un typo en las descripciones en ingles seria an user en vez de a user (agregar la n antes de una vocal)

Lo que llevamos hasta ahora:

Main

# Python
from typing import List, Dict

# Models
from models import User, UserLogin, Tweet

# FastAPI
from fastapi import status
from fastapi import FastAPI

app = FastAPI()

# Path Operations

@app.get(
    path='/',
    tags=['Home'])
def home() -> Dict[str, str]:
    """
    Home Route

    Show a message explaining if Twitter API is working

    Parameters:
    - None

    Returns JSON key: 'Twitter API' and JSON value: 'Working'
    """
    return {'Twitter API': 'Working'}

## Users

@app.post(
    path='auth/singup',
    response_model=User,
    status_code=status.HTTP_201_CREATED,
    summary='Register a user',
    tags=['Auth', 'users']
)
def singup(

):
    pass

@app.post(
    path='auth/login',
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary='Login a user',
    tags=['Auth', 'users']
)
def login(
    
):
    pass

@app.get(
    path='/users',
    response_model=List[User],
    status_code=status.HTTP_200_OK,
    summary='Show all user',
    tags=['users']
)
def show_all_users(
    
):
    pass

@app.get(
    path='/users/{user_id}',
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary='Show a user',
    tags=['users']
)
def show_a_users(
    
):
    pass

@app.delete(
    path='/users/{user_id}/delete',
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary='Delete a user',
    tags=['users']
)
def delete_a_user(
    
):
    pass

@app.put(
    path='/users/{user_id}/update',
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary='Update a user',
    tags=['users']
)
def Update_a_user(
    
):
    pass

## Tweets

Super Este Curso

## Users

@app.post(
    path='/signup',
    response_model=User,
    status_code=status.HTTP_201_CREATED,
    summary='Register an User',
    tags=['Users']
)
def signup():
    pass

@app.post(
    path='/login',
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary='Login an User',
    tags=['Users']
)
def login():
    pass

@app.get(
    path='/users',
    response_model=List[User],
    status_code=status.HTTP_200_OK,
    summary='Show all users',
    tags=['Users']
)
def show_all_users():
    pass

@app.get(
    path='/users/{user_id}',
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary='Show an User',
    tags=['Users']
)
def show_an_user():
    pass

@app.delete(
    path='/users/{user_id}/delete',
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary='Delete an User',
    tags=['Users']
)
def delete_an_user():
    pass

@app.put(
    path='/users/{user_id}/update',
    response_model=User,
    status_code=status.HTTP_200_OK,
    summary='Update an User',
    tags=['Users']
)
def update_an_user():
    pass