tiangolo/fastapi

What is the differance between FastApi Depends and pydantic BaseModel

ShukurovOzodbek opened this issue · 1 comments

Privileged issue

  • I'm @tiangolo or he asked me directly to create an issue here.

Issue Content

Hi everyone, can you explain me this topic and when use pydanctic BaseModel and when Depends

  1. Depends:
    Depends is mainly used for declaring dependencies, such as obtaining a database connection or validating a user. It helps you organize and reuse code in a declarative manner.
from fastapi import FastAPI, Depends

app = FastAPI()

def get_db():
    return {"db": "database_connection"}

@app.get("/items/")
async def read_items(db: dict = Depends(get_db)):
    return db
  1. BaseModel:
    BaseModel is primarily used for data validation and data transformation. You can define a model and then use that model to validate input and output data.
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

item = Item(name="Bread", price=0.5)

In these examples, Depends is used to get a database connection, while BaseModel is used to validate item data.

  1. main.py:
    This program demonstrates the different uses of Depends and BaseModel. Depends is used for dependency injection, which can help you extract and preprocess some data from the request (such as validation). BaseModel from the pydantic library is used for data validation and data conversion, helping you define data models and ensure data conforms to the expected format. In this program, Depends is utilized to get and validate HTTP credentials, while BaseModel is used to define and validate the user data model.
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel

app = FastAPI()
security = HTTPBasic()

class User(BaseModel):
    username: str
    password: str

def get_current_user(credentials: HTTPBasicCredentials = Depends(security)) -> User:
    valid_users = {"Alice": "alice_passwd"}
    if credentials.username not in valid_users or valid_users[credentials.username] != credentials.password:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    return User(username=credentials.username, password=credentials.password)

@app.post("/users/")
async def read_users(user: User = Depends(get_current_user)):
    return user

3.1 Verify main.py

$ uvicorn main:app --reload
INFO:     Will watch for changes in these directories: ['/private/tmp']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [79904] using WatchFiles
INFO:     Started server process [79931]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:58203 - "POST /users/ HTTP/1.1" 200 OK
INFO:     127.0.0.1:58207 - "POST /users/ HTTP/1.1" 401 Unauthorized

$ curl -X POST "http://127.0.0.1:8000/users/" -H "accept: application/json" -u Alice:alice_passwd
{"username":"Alice","password":"alice_passwd"}

$curl -X POST "http://127.0.0.1:8000/users/" -H "accept: application/json" -u Alice:alice_password
{"detail":"Unauthorized"}