question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How could I return default value with response_model

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from pydantic import BaseModel
from typing import List, Optional
from fastapi import FastAPI

app = FastAPI()

class Users(BaseModel):
    name: Optional[str] = 'No Username'

@app.get("/", response_model=List[Users])
async def get_users():
    users = [{'id':1, 'name':'abc'},{'id':2, 'name':None}]
    return users

Description

I want to return the imformation of all users. If an user didn’t set his name(None), then return ‘No username’.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.66.1

Python Version

3.9.5

Additional Context

No response

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

2reactions
Honda-acommented, Sep 9, 2021

I see then in that case you need to set your default value in the Model and use pydantic_model_creator it would be something like this

from tortoise.models import Model
from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
class ModelUsers(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField(null=True, default="No Username")

Users = pydantic_model_creator(ModelUsers, name="Users")

@app.get("/", response_model=List[Users])
async def get_users():
    users = await pydantic_model_creator.from_queryset(ModelUsers.all())
    return users
0reactions
skk294commented, Sep 10, 2021

I see then in that case you need to set your default value in the Model and use pydantic_model_creator it would be something like this

from tortoise.models import Model
from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
class ModelUsers(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField(null=True, default="No Username")

Users = pydantic_model_creator(ModelUsers, name="Users")

@app.get("/", response_model=List[Users])
async def get_users():
    users = await pydantic_model_creator.from_queryset(ModelUsers.all())
    return users

Thank you. ^_^

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to return a default value in the response? - Stack Overflow
One way to do it is to define it as an enum with a single value: openapi: 3.0.0 info: title: Sample API description:...
Read more >
Response Model - FastAPI
Use response_model_exclude_unset to return only the values explicitly set. Previous Header Parameters · Next Extra Models.
Read more >
value expressions - produce the default value for any type
In this article. A default value expression produces the default value of a type. There are two kinds of default value expressions: the...
Read more >
3 Ways to Set Default Value in JavaScript | SamanthaMing.com
Let's break down the 3 different ways to set Default Values using logical operator, ternary, and if/else...
Read more >
Change Request Model does not return the correct default ...
Where there is an amended default value for change requests state, so other than -5, there is a method that gets the initial...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found