Skip to main content

Pydantic (Data Validation) in FastAPI


When a client sends data to your API (like a form), you often want it to be structured. FastAPI uses Pydantic models to define this structure.

1. Define a Pydantic Model

A Pydantic model is a Python class that describes what the data should look like:

from fastapi import FastAPI
from typing import List
from pydantic import BaseModel, Field

app = FastAPI()

class Student(BaseModel):
    id: int
    name: str = Field(None, title="Name of the student", max_length=10)
    subjects: List[str] = []

Here:

  • id is an integer
  • name is a string (max 10 characters)
  • subjects is a list of strings, default empty

2. Use POST to Accept the Model

To get data from a client, use the POST method:

@app.post("/students/")
async def student_data(s1: Student):
    return s1

Explanation:

  • @app.post("/students/") defines the URL and POST method
  • s1: Student tells FastAPI to expect a JSON body matching the Student model
  • The function returns the same data back as JSON

3. Test in Swagger UI

  1. Start the server: uvicorn main:app --reload
  2. Open in browser: http://localhost:8000/docs
  3. Find the /students/ route under POST
  4. Click Try it out, fill in test data, and click Execute
  5. You get a JSON response with the same data you sent

4. Using Individual Fields Instead of a Model

You can accept individual fields using Body:

from fastapi import Body

@app.post("/students")
async def student_data(name: str = Body(...), marks: int = Body(...)):
    return {"name": name, "marks": marks}

- `name` and `marks` are sent in the request body separately

- Works the same as the model, just with individual fields

5. Combining Path, Query, and Body

@app.post("/students/{college}")
async def student_data(college: str, age: int, student: Student):
    retval = {"college": college, "age": age, **student.dict()}
    return retval

Explanation:

  • college → path parameter (`/students/XYZ`)
  • age → query parameter (`?age=20`)
  • student → JSON request body (Pydantic model)
  • **student.dict() → converts the Student object to a dictionary

Example request:

POST /students/ABC?age=20
{
  "id": 1,
  "name": "Alice",
  "subjects": ["Math", "Physics"]
}

Response:

{
  "college": "ABC",
  "age": 20,
  "id": 1,
  "name": "Alice",
  "subjects": ["Math", "Physics"]
}

Summary

  • Use Pydantic models to structure request body data.
  • Use Body(...) for individual fields.
  • POST method is used to receive request body.
  • You can combine path + query + body in a single endpoint.
  • FastAPI automatically validates data and converts JSON to Python objects.


Contact Us

Name

Email *

Message *

Popular Posts

Online Simulator for ASK, FSK, and PSK Signal Generation

Interactive Digital Signal Processing (DSP) Tutorial and Simulator for ASK, FSK, and BPSK modulation techniques. Try our new Digital Signal Processing Simulator!   •   Interactive ASK, FSK, and BPSK tools updated for 2025. Start Now Digital Modulation Visualizer: ASK, FSK, & BPSK Simulator Learn and visualize binary modulation techniques (ASK, FSK, BPSK) in real-time with adjustable carrier and sampling parameters. Perfect for DSP students and engineers. 📡 ASK Simulator 📶 FSK Simulator 🎚️ BPSK Simulator 📚 More Topics ASK Modulator FSK Modulator BPSK Modulator Demodulation More Topics 1. ASK (Ampli...

UGC NET Electronic Science Previous Year Question Papers with Solutions

Download Papers and Solutions Exam Pattern Preparation Tips FAQs More Home / Engineering & Other Exams / UGC NET 2026 PYQ 📊 Exam Highlights: Electronic Science (88) Feature Details Junior Research Fellowship (JRF) ₹37,000 + HRA per month Eligibility M.Sc/M.Tech in Electronics (55%) Validity of Certificate JRF (3 Years) | Lectureship (Lifetime) 📥 Download UGC NET Electronics PDFs Complete collection of previous year question papers, answer keys and explanations for Subject Code 88. Start Downloading 📂 View All Question Papers June 2025 - Question Paper Download PDF June 2025 - Sol...

DFTs-OFDM vs OFDM: Why DFT-Spread OFDM Reduces PAPR Effectively (with MATLAB Code)

Understanding PAPR in DFT-spread OFDM vs. Standard OFDM In modern wireless communications like 4G LTE and 5G NR, managing the Peak-to-Average Power Ratio (PAPR) is critical for hardware efficiency. While OFDM is the gold standard for high-speed data, its high PAPR poses significant challenges for mobile devices. This is where DFTs-OFDM (also known as SC-FDMA) comes in. DFT-spread OFDM (DFTs-OFDM) has lower Peak-to-Average Power Ratio (PAPR) because it "spreads" the data in the frequency domain before applying IFFT, making the time-domain signal behave more like a single-carrier signal rather than a multi-carrier one like OFDM. Deeper Explanation: Aspect OFDM DFTs-OFDM Signal Type Multi-carrier Single-carrier-like Process IFFT of QAM directly QAM → DFT → IFFT PAPR Level High (due to many...

Constellation Diagrams of ASK, PSK, and FSK (with MATLAB Code + Simulator)

Constellation Diagrams: ASK, FSK, and PSK Comprehensive guide to signal space representation, including interactive simulators and MATLAB implementations. 📘 Overview 🧮 Simulator ⚖️ Theory 📈 Q-function 📚 Resources BASK Modulation Transmits one of two signals: 0 or $\sqrt{E_b}$, representing binary 0 and 1. Simple but sensitive to noise. BFSK Modulation Transmits one of two signals: $\sqrt{E_b}$ on the Y-axis or $\sqrt{E_b}$ on the X-axis. These are orthogonal signals. BPSK Modulation Transmits $+\sqrt{E_b}$ or $-\sqrt{E_b}$ (antipodal signaling). Most efficient binary scheme. ...

Calculation of SNR from FFT bins in MATLAB

📘 Overview 💻 FFT Bin Method 💻 Kaiser Window 📚 Further Reading SNR Estimation Overview In digital signal processing, estimating the Signal-to-Noise Ratio (SNR) accurately is crucial. Below, we demonstrate how to calculate SNR from periodogram and FFT bins using the Kaiser Window . The beta (β) parameter is the key—it allows you to control the trade-off between main-lobe width and side-lobe levels for precise spectral analysis. 1 Define Sampling rate and Time vector 2 Compute FFT and Periodogram PSD 3 Identify Signal Bin and Frequency resolution 4 Segment Signal Power from Noise floor 5 Logarithmic calculation of SNR in dB Method 1: Estimation from FFT Bins This approach uses a Hamming window to estimate SNR directly from the spectral bins. MATLAB Source Code Copy Code clc...

Advanced M-ary Modulation Simulator: Constellation, min dist, Efficiency, SER, EVM (RMS)

Advanced M-ary Communication Lab Analytical & Statistical Performance of Digital Modulation Theoretical Probability of Error (\(P_s\)) \[ P_s = Q\left(\sqrt{\frac{2 E_b}{N_0}}\right) \] Modulation (M-ary) BPSK (M=2) QPSK (M=4) 8-PSK (M=8) 16-QAM (M=16) 64-QAM (M=64) 256-QAM (M=256) SNR (\(E_b/N_0\)): 12 dB Efficiency 2 bps/Hz Min Dist (\(d_{min}\)) 1.41 Symbol Error 1.2e-5 EVM (RMS) 0.0% Constellation Diagram Noise PDF & Decision Tail 1. Geometric Mapping ...

OFDM Symbols and Subcarriers Explained

This article explains how OFDM (Orthogonal Frequency Division Multiplexing) symbols and subcarriers work. It covers modulation, mapping symbols to subcarriers, subcarrier frequency spacing, IFFT synthesis, cyclic prefix, and transmission. Step 1: Modulation First, modulate the input bitstream. For example, with 16-QAM , each group of 4 bits maps to one QAM symbol. Suppose we generate a sequence of QAM symbols: s0, s1, s2, s3, s4, s5, …, s63 Step 2: Mapping Symbols to Subcarriers Assume N sub = 8 subcarriers. Each OFDM symbol in the frequency domain contains 8 QAM symbols (one per subcarrier): Mapping (example) OFDM symbol 1 → s0, s1, s2, s3, s4, s5, s6, s7 OFDM symbol 2 → s8, s9, s10, s11, s12, s13, s14, s15 … OFDM sym...