/FAST_and_HAPPY

FastAPI

Primary LanguagePython

FastAPI

Api with authentication : step by step

Another

1. Exceptions : HTTPException

https://umbraco.com/knowledge-base/http-status-codes/

Example

from fastapi.exceptions import HTTPException
...
image_url_types = ['absolute', 'relative']


@router.post('', response_model=PostDisplay)
def create(request: PostBase, db: Session = Depends(get_db), current_user: UserAuth = Depends(get_current_user)):
    if not request.image_url_type in image_url_types:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                            detail="Le paramètre de image_url_type peut seulement prendre une valeur absolue('absolute') ou relative('relative'). ")
    return db_post.create(db, request)

2. Regex

from fastapi import APIRouter, Query, Path, Body
from pydantic import BaseModel
from typing import Optional, List, Dict
...
@router.post('/new/{id}/comment/{comment_id}')
def create_comment(blog: BlogModel, id: int,
                   comment_title: int = Query(None,
                                              title='Id of the comment',
                                              description='Some description for comment_id',
                                              alias='commentId',
                                              deprecated=True),
                   content: str = Body(..., min_length=10, max_length=100, regex='^[a-z\s]*$'),
                   v: Optional[List[str]] = Query(['1.0', '2.0', '3.0']),
                   comment_id: int = Path(None, gt=5, le=10),
                   ):
    return {
        'blog': blog,
        'id': id,
        'comment_title': comment_title,
        'comment_id': comment_id,
        'content': content,
        'version': v
    }

https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s09.html

3. Validator and Number Validators