READ-ONLY PACKAGE PREVIEW

fastapi/examples/public_contract.py

Version 0.142.2.bb1 · MIT. This preview displays packaged text and does not execute code. Treat the contents as untrusted instructions.

← Return to resource and package checksum

"""BB Skills synthetic contracts and an explicit raw-Response counterexample.

Exercise only through TestClient. This is not an authenticated production API.
"""
from typing import Any
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel,ConfigDict,Field

class ProductInput(BaseModel):
    model_config=ConfigDict(extra='forbid')
    name:str=Field(min_length=1)
    cost:float=Field(gt=0)

class PublicProduct(BaseModel):
    name:str
    cost:float

def create_example_app():
    app=FastAPI()

    @app.post('/products',response_model=PublicProduct)
    def create_product(product:ProductInput)->Any:
        return {**product.model_dump(),'internal_note':'synthetic local-only field'}

    @app.get('/broken',response_model=PublicProduct)
    def broken_response()->Any:
        return {'name':'Fixture'}  # Intentional server-side contract violation.

    @app.get('/direct-response',response_model=PublicProduct)
    def direct_response_counterexample()->Any:
        # Intentional counterexample: a Response object bypasses model filtering.
        return JSONResponse({'name':'Fixture','cost':1,'internal_note':'synthetic local-only field'})

    return app