0
0
FastAPIframework~30 mins

List and set validation in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
List and Set Validation with FastAPI
📖 Scenario: You are building a simple FastAPI app that accepts user input for favorite fruits. You want to make sure the input is a list of fruits and also check if the fruits are unique using a set.
🎯 Goal: Create a FastAPI endpoint that accepts a list of fruits, validates it, and converts it to a set to ensure uniqueness.
📋 What You'll Learn
Create a list variable called fruits with exact values: ['apple', 'banana', 'apple', 'orange']
Create a variable called unique_fruits that converts fruits to a set
Create a FastAPI app instance called app
Create a POST endpoint /fruits that accepts a list of strings called fruits in the request body
💡 Why This Matters
🌍 Real World
Validating lists and sets is common when handling user input in web apps, such as filtering unique items or preferences.
💼 Career
Backend developers often use FastAPI to build APIs that validate and process list data efficiently.
Progress0 / 4 steps
1
Create the initial list of fruits
Create a list variable called fruits with these exact values: ['apple', 'banana', 'apple', 'orange']
FastAPI
Need a hint?

Use square brackets to create a list and include the fruits exactly as shown.

2
Convert the list to a set for uniqueness
Create a variable called unique_fruits that converts the list fruits to a set using set(fruits)
FastAPI
Need a hint?

Use the set() function to remove duplicates from the list.

3
Create a FastAPI app instance
Import FastAPI from fastapi and create an app instance called app using app = FastAPI()
FastAPI
Need a hint?

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

4
Create a POST endpoint to accept a list of fruits
Create a POST endpoint /fruits using @app.post('/fruits') that accepts a parameter fruits of type list[str] in the request body and returns the set of unique fruits using set(fruits)
FastAPI
Need a hint?

Use @app.post('/fruits') decorator and define an async function with parameter fruits: List[str]. Return the unique fruits as a list inside a dictionary.