0
0
FastAPIframework~30 mins

Dependencies with parameters in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
FastAPI Dependencies with Parameters
📖 Scenario: You are building a simple FastAPI app that greets users differently based on a greeting style parameter.This is like choosing how you say hello to a friend: formally, casually, or excitedly.
🎯 Goal: Create a FastAPI app that uses a dependency with a parameter to customize the greeting message.The app will have one endpoint /greet/ that returns a greeting message based on the style passed as a query parameter.
📋 What You'll Learn
Create a FastAPI app instance called app.
Define a dependency function get_greeting_style that accepts a parameter style from the query string.
Use the dependency in the /greet/ endpoint to return a greeting message based on the style.
Support greeting styles: 'formal', 'casual', and 'excited'.
💡 Why This Matters
🌍 Real World
Using dependencies with parameters in FastAPI helps you write clean, reusable code that can customize behavior based on user input, like greeting styles or user roles.
💼 Career
Understanding FastAPI dependencies with parameters is essential for backend developers building scalable and maintainable APIs that adapt to different client needs.
Progress0 / 4 steps
1
Create the FastAPI app instance
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Need a hint?

Use from fastapi import FastAPI and then app = FastAPI().

2
Define the dependency function with a parameter
Define a function called get_greeting_style that takes a parameter style of type str with a default value of "casual". Import Query from fastapi and use it to get style from the query parameters.
FastAPI
Need a hint?

Use def get_greeting_style(style: str = Query("casual")) and return style.

3
Create the /greet/ endpoint using the dependency
Create a GET endpoint /greet/ using @app.get("/greet/"). Define a function greet that takes a parameter style which uses the dependency get_greeting_style with Depends. Import Depends from fastapi. Inside the function, return a dictionary with key message and value based on style: if style is 'formal', return 'Good day to you.'; if 'casual', return 'Hey there!'; if 'excited', return 'Hello!!!'.
FastAPI
Need a hint?

Use @app.get("/greet/") and def greet(style: str = Depends(get_greeting_style)). Return a dictionary with the correct message based on style.

4
Add type hints and import statements for completeness
Add the import statement for Depends from fastapi if missing. Ensure all functions have proper type hints: get_greeting_style returns str, greet returns a dictionary with str keys and values. This completes the FastAPI app with dependency injection using parameters.
FastAPI
Need a hint?

Make sure to import Depends and add return type hints for both functions.