0
0
FastAPIframework~5 mins

Default values in FastAPI

Choose your learning style9 modes available
Introduction

Default values let you set a fallback for function parameters. This means if someone does not give a value, your code still works smoothly.

When you want an API endpoint to have optional query parameters.
When you want to provide a common default setting for a function argument.
When you want to avoid errors if a user forgets to send some data.
When you want to simplify your API by not forcing all inputs every time.
Syntax
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/items")
async def read_items(q: str = "default"):
    return {"q": q}

Set default values by using = value after the parameter name.

If the client does not send the parameter, FastAPI uses the default.

Examples
This example sets a default limit of 10 users if no limit is provided.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/users")
async def get_users(limit: int = 10):
    return {"limit": limit}
Here, the query parameter is optional. If missing, the function returns a message.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/search")
async def search_items(query: str = None):
    if query:
        return {"query": query}
    return {"message": "No query provided"}
Sample Program

This FastAPI app has one endpoint /greet. It greets the user by name. If no name is given, it says "Hello, friend!" by default.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/greet")
async def greet(name: str = "friend"):
    return {"message": f"Hello, {name}!"}
OutputSuccess
Important Notes

Default values must be simple types like strings, numbers, or None.

Using default values makes your API easier to use and more flexible.

Summary

Default values provide fallback inputs for function parameters.

They make parameters optional in FastAPI endpoints.

Use them to avoid errors and simplify your API design.