swadhinbiswas docs: build docs_site — restructure sidebar, create 37 new pages · 7/25/2026
98106de
77 lines · 1.8 KB
Raw Download

title: Response Model — Return Type
description: Control the response schema and filter output fields in JustAPI with response_model.
keywords: [JustAPI, response model, return type, filtering, schema]

Basic Response Model

Declare the response type with response_model:

from pydantic import BaseModel
from justapi import JustAPIApp

class User(BaseModel):
    id: int
    name: str
    email: str
    password: str

app = JustAPIApp()

@app.get("/users/{user_id}", response_model=User)
def get_user(user_id: int):
    return {"id": user_id, "name": "Alice", "email": "[email protected]", "password": "secret"}

The password field is automatically excluded from the response because it's not declared in the response model.

Filtering Response Fields

class UserOut(BaseModel):
    id: int
    name: str

@app.get("/users/{user_id}", response_model=UserOut)
def get_user(user_id: int):
    return {"id": user_id, "name": "Alice", "email": "[email protected]"}

Only id and name appear in the response.

Exclude Fields

@app.get(
    "/users/{user_id}",
    response_model=User,
    response_model_exclude={"password"},
)
def get_user(user_id: int):
    return {"id": user_id, "name": "Alice", "email": "[email protected]", "password": "secret"}

Multiple Response Models

from typing import Union

@app.get(
    "/users/{user_id}",
    response_model=Union[UserOut, dict],
    responses={404: {"model": dict}},
)
def get_user(user_id: int):
    if user_id == 0:
        return {"error": "not found"}
    return {"id": user_id, "name": "Alice"}

See Also