Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Sichere ProgrammierungRate Limiting: The Traffic Cop Your API Needs(20.09.2026 um 14:51 Uhr)
Sichere ProgrammierungI Built the MVP First. Then I Wrote the README.(20.09.2026 um 14:51 Uhr)
Sichere ProgrammierungHow to add a loading screen with a progress bar in Godot 4(20.09.2026 um 14:52 Uhr)
Sichere ProgrammierungCanada is about to break your scheduler(20.09.2026 um 14:59 Uhr)
Sichere ProgrammierungWhat Does an AI Automation Agency Actually Do?(20.09.2026 um 15:00 Uhr)
Sichere ProgrammierungRate Limiting: The Traffic Cop Your API Needs(20.09.2026 um 14:51 Uhr)
Sichere ProgrammierungI Built the MVP First. Then I Wrote the README.(20.09.2026 um 14:51 Uhr)
Sichere ProgrammierungHow to add a loading screen with a progress bar in Godot 4(20.09.2026 um 14:52 Uhr)
Sichere ProgrammierungCanada is about to break your scheduler(20.09.2026 um 14:59 Uhr)
Sichere ProgrammierungWhat Does an AI Automation Agency Actually Do?(20.09.2026 um 15:00 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

# 🚀 Validating User Input with FastAPI: An Example with Custom Validators

Reagiere als Erste:r — dein Feedback zählt!

When building an API, validating user input is critical for maintaining data integrity and providing a great user experience. With FastAPI and Pydantic, you can easily validate incoming data and provide clear feedback to users.

In this article, we'll build a simple User Management API with custom validators for:

  • Ensuring the email field is a valid email.
  • Checking that name contains at least 3 characters.
  • Verifying that age is at least 18 years.

Let's dive in! 🏊‍♂️

🏗 Prerequisites

Before you start, ensure you have the following:

  • Python 3.8+
  • pip (Python package manager)

Install the required libraries:

pip install fastapi uvicorn pydantic

📜 The API Features

We'll build an API that:

  1. Accepts user data: Name, Email, and Age.
  2. Validates input data:
    • Name must have at least 3 characters.
    • Email must be a valid email address.
    • Age must be 18 or older.
  3. Stores users: In-memory for simplicity.
  4. Provides feedback: Returns clear error messages when validation fails.

🛠 Code Implementation

1️⃣ Define the User Model with Validators

We’ll use Pydantic to define the input model and implement custom validation.

from pydantic import BaseModel, EmailStr, validator

class UserCreate(BaseModel):
    name: str
    email: EmailStr  # Automatically validates email format
    age: int

    # Validator to ensure the name has at least 3 characters
    @validator("name")
    def name_must_be_valid(cls, value):
        if len(value) < 3:
            raise ValueError("Name must contain at least 3 characters.")
        return value

    # Validator to ensure the age is at least 18
    @validator("age")
    def age_must_be_adult(cls, value):
        if value < 18:
            raise ValueError("Age must be at least 18 years old.")
        return value

2️⃣ Initialize the FastAPI App and User Store

We'll create an in-memory list to store users and define the API endpoints.

from fastapi import FastAPI, HTTPException
from typing import List

app = FastAPI()

# In-memory user storage
users = []

@app.post("/users/", response_model=UserCreate)
def create_user(user: UserCreate):
    # Check if email is already registered
    if any(u['email'] == user.email for u in users):
        raise HTTPException(status_code=400, detail="Email already registered")

    # Add user to the in-memory database
    users.append(user.dict())
    return user


@app.get("/users/", response_model=List[UserCreate])
def get_users():
    return users

 3️⃣ Run the Application

Run the app using Uvicorn:

uvicorn main:app --reload

Visit the interactive API documentation at http://127.0.0.1:8000/docs.

🎯 Testing the API

Here’s how you can test the API using cURL or any HTTP client like Postman or Thunder Client.

✅ Valid Request

curl -X POST "http://127.0.0.1:8000/users/" \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "[email protected]", "age": 25}'

Response:

{
  "name": "John Doe",
  "email": "[email protected]",
  "age": 25
}

❌ Invalid Email

curl -X POST "http://127.0.0.1:8000/users/" \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "invalid-email", "age": 25}'

Response:

{
  "detail": [
    {
      "loc": ["body", "email"],
      "msg": "value is not a valid email address",
      "type": "value_error.email"
    }
  ]
}

❌ Name Too Short

curl -X POST "http://127.0.0.1:8000/users/" \
-H "Content-Type: application/json" \
-d '{"name": "Jo", "email": "[email protected]", "age": 25}'

Response:

{
  "detail": [
    {
      "loc": ["body", "name"],
      "msg": "Name must contain at least 3 characters.",
      "type": "value_error"
    }
  ]
}

❌ Age Below 18

curl -X POST "http://127.0.0.1:8000/users/" \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "[email protected]", "age": 15}'

Response:

{
  "detail": [
    {
      "loc": ["body", "age"],
      "msg": "Age must be at least 18 years old.",
      "type": "value_error"
    }
  ]
}

 ❌ Email Already Registered

First, create a user with the following request:

curl -X POST "http://127.0.0.1:8000/users/" \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "[email protected]", "age": 25}'

Then, try creating another user with the same email:

curl -X POST "http://127.0.0.1:8000/users/" \
-H "Content-Type: application/json" \
-d '{"name": "Jane Doe", "email": "[email protected]", "age": 30}'

 Response:

{
  "detail": "Email already registered"
}

🌟 Key Features of This Example

  1. Validation with Pydantic:

    • Automatic validation for email format.
    • Custom validators for name and age.
  2. Clear Error Messages:

    • Each validation error is returned with a specific message, making it easier to debug and fix input issues.
  3. Scalable Design:

    • The approach can be extended to include more fields, validations, or even integrate a database.

🚀 Wrapping Up

Using FastAPI and Pydantic, you can implement powerful validation logic with minimal effort. This approach not only ensures data integrity but also improves the developer and user experience with clear and actionable error messages.

What custom validators would you add to this API? Share your thoughts in the comments! 🎉

Happy coding! 👨‍💻👩‍💻

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten # 🚀 Validating User Input with FastAPI: An Example with Custom Validators

Thematisch verwandte Begriffe: Validating, User, Input, with · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-93956 | A flaw has been found in olivier-ls PHP-FTS up to 1.1.2. Affected by thi…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick