How could I return default value with response_model
See original GitHub issueFirst 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:
- Created 2 years ago
- Comments:5
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
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 thisThank you. ^_^