Code Monkey home page Code Monkey logo

Comments (4)

tiangolo avatar tiangolo commented on April 28, 2024

Here the thing is that even if you return a dict with the data as you want it, FastAPI will try to pass it to the Model in response_model and re-serialize it with that model.

But if instead of returning a Pydantic model or a dict you return a Starlette Response, it will use it as is.

Here's one way you could solve it (your same code and data requirements, but the tests pass):

from fastapi.encoders import jsonable_encoder
import json
from typing import List

from fastapi import FastAPI
from pydantic import BaseModel, Schema

import pytest
from starlette.testclient import TestClient
from starlette.responses import JSONResponse

app = FastAPI()


class Model(BaseModel):
    model_field: str = Schema(..., alias="modelField")

    class Config:
        allow_population_by_alias = True


@app.get("/models", response_model=List[Model])
def get_models():
    m = Model(model_field="string")
    content = jsonable_encoder([
        Model(model_field=m.model_field),
        Model(modelField=m.model_field),
        Model(**m.dict()),
        Model(**m.dict(by_alias=True)),
    ], by_alias=True)
    return JSONResponse(content=content)


@app.post("/models", response_model=Model)
def create_model(m: Model):
    content = jsonable_encoder(Model(**m.dict()), by_alias=True)
    return JSONResponse(content=content)


@pytest.fixture
def client():
    yield TestClient(app)


def test_get_models(client):
    with client:
        response = client.get("/models")
    assert response.json() == [{"modelField": "string"} for _ in range(4)]


def test_create_model(client):
    with client:
        response = client.post("/models", json.dumps({"modelField": "string"}))
    assert response.json() == {"modelField": "string"}

from fastapi.

nsidnev avatar nsidnev commented on April 28, 2024

Thanks! I changed my code and now it works as I want

from fastapi.

tiangolo avatar tiangolo commented on April 28, 2024

Great! Thanks for reporting back and closing the issue.

from fastapi.

github-actions avatar github-actions commented on April 28, 2024

Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.

from fastapi.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.