# FastAPI Response Model via Pydantic

* There are times where you don't want all the data sent back to the user
* This is where you would want to define how the response looks like
* In the <mark style="color:green;">`schemas.py`</mark> we will define the Pydantic model for the response

```python
from pydantic import BaseModel

# Note: This file is used to define Pydantic models
# Used for POST and RESPONSE in FastAPI

# The below code handles the user sending data to us
class PostBase(BaseModel):
    title: str
    content: str
    published: bool = True

class PostCreate(PostBase):
    pass

# The below code handles us sending data back to the user
class PostResponse(BaseModel):
    title: str
    content: str
    published: bool
```

* This will return only the fields specified in the <mark style="color:orange;">`PostResponse`</mark> class
* We will also have to define the <mark style="color:blue;">`response_model`</mark> in the app decorator

```python
@app.post("/posts", status_code=status.HTTP_201_CREATED, response_model=schemas.PostResponse)
def create_posts(post: schemas.PostCreate, db: Session = Depends(get_db)):

    new_post = models.Post(**post.dict())
    db.add(new_post)
    db.commit()
    db.refresh(new_post)

    return new_post
```

* This will still not work fully as our Pydantic model only knows how to work with dictionary's&#x20;
* The issue here is that when we make the query, <mark style="color:blue;">`new_post`</mark> is a SQLAlchemy model
* Pydantic has no idea what to do with that, so the SQLAlchemy model has to be converted to a Pydantic model
* More information about this: [Click here!](https://fastapi.tiangolo.com/tutorial/sql-databases/?h=)
* To do that we will have to pass the following code

```python
class Config:
        orm_mode = True
```

* This will tell Pydantic to convert it, even if it's not a valid dict
* So the new class in <mark style="color:green;">`schemas.py`</mark> should look like this

```python
class PostResponse(BaseModel):
    title: str
    content: str
    published: bool

    class Config:
        orm_mode = True
```

* Now this should work and return our correct response

![](https://3885248957-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoE4wMO1dMVDOGDjh0En7%2Fuploads%2FIJpuPnd5iW4OKYxDKCoI%2Fimage.png?alt=media\&token=7cbc6dbe-671f-47e1-b999-b317259f7c5e)

* When retrieving a list, just passing in the normal decorator parameter <mark style="color:purple;">`schemas.PostResponse`</mark> will not work
* We need to convert this to a List with from the typing library
* How it should look: <mark style="color:purple;">`List[schemas.PostResponse]`</mark>

```python
@app.get("/posts", response_model=List[schemas.PostResponse])
def get_posts(db: Session = Depends(get_db)):

    posts = db.query(models.Post).all()

    return posts
```
