0
0
FastAPIframework~30 mins

String validation (min, max, regex) in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
String validation (min, max, regex) with FastAPI
📖 Scenario: You are building a simple web API using FastAPI. The API will accept a username from users. You want to make sure the username is valid by checking its length and pattern.
🎯 Goal: Create a FastAPI app that accepts a username string with these rules: minimum length 3, maximum length 10, and only letters and numbers allowed. Use Pydantic string validation with min_length, max_length, and regex.
📋 What You'll Learn
Create a FastAPI app instance called app
Create a Pydantic model called User with a username field
Validate username with min_length=3, max_length=10, and a regex that allows only letters and numbers
Create a POST endpoint /users/ that accepts a User model and returns the username
💡 Why This Matters
🌍 Real World
Validating user input is essential in web APIs to prevent bad data and security issues. FastAPI with Pydantic makes this easy and clear.
💼 Career
Backend developers often need to validate incoming data. Knowing how to use FastAPI and Pydantic validation is a valuable skill for building reliable APIs.
Progress0 / 4 steps
1
Create FastAPI app and User model with username field
Write code to import FastAPI and BaseModel from pydantic. Create a FastAPI app instance called app. Create a Pydantic model called User with a single field username of type str.
FastAPI
Need a hint?

Start by importing FastAPI and BaseModel. Then create app = FastAPI(). Define User class inheriting from BaseModel with a username field of type str.

2
Add validation rules to username field
Modify the username field in the User model to add validation: set min_length=3, max_length=10, and a regex pattern that allows only letters and numbers. Use Field(..., min_length=3, max_length=10, regex="^[a-zA-Z0-9]+$").
FastAPI
Need a hint?

Import Field from pydantic. Use Field(..., min_length=3, max_length=10, regex="^[a-zA-Z0-9]+$") to add validation to username.

3
Create POST endpoint to accept User model
Add a POST endpoint /users/ to the FastAPI app. The endpoint should accept a User model as input and return a dictionary with the key username and the value from the input model.
FastAPI
Need a hint?

Use @app.post("/users/") decorator. Define async function create_user with parameter user: User. Return dictionary with username key and user.username value.

4
Add response model to endpoint
Modify the POST endpoint /users/ to include a response_model=User parameter in the decorator. This ensures the response matches the User model.
FastAPI
Need a hint?

Add response_model=User inside the @app.post decorator parentheses.