Skip to main content

Understanding Paths, Parameters, and Validation in FastAPI


Understanding Paths, Parameters, and Validation in FastAPI

Understanding Paths, Parameters, and Validation in FastAPI

Modern web frameworks, including FastAPI, use routes or endpoints as part of the URL instead of file-based URLs. This approach makes URLs easier to remember and more meaningful for users. In FastAPI, a path or route refers to the part of the URL that comes after the first slash (/).

What is a Path in FastAPI?

Consider the URL:

http://localhost:8000/hello/TutorialsPoint

Here, the path is:

/hello/TutorialsPoint

In FastAPI, you define paths using operation decorators, which correspond to HTTP verbs like GET, POST, PUT, or DELETE. The decorator is followed by a function called a path operation function, which executes when the URL is visited.

Example: Basic Path Operation

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def index():
    return {"message": "Hello World"}
  • "/" → the path
  • get → the HTTP operation
  • @app.get("/")path operation decorator
  • index()path operation function

HTTP Methods in FastAPI

MethodDescription
GETRetrieve data from the server (most common)
HEADLike GET but without the response body
POSTSend data to the server, typically form data
PUTReplace the current representation of a resource
DELETERemove the resource identified by the URL

The async keyword allows the function to run asynchronously, without blocking other requests, though it’s optional.

Path Parameters

Paths can contain variable parameters, which allow URLs to accept dynamic data. Parameters are enclosed in curly braces {}.

Example: Single Path Parameter

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello/{name}")
async def hello(name):
    return {"name": name}

URL: http://localhost:8000/hello/Tutorialspoint

{"name":"Tutorialspoint"}

Change Tutorialspoint to Python:

{"name":"Python"}

Multiple Path Parameters

@app.get("/hello/{name}/{age}")
async def hello(name, age):
    return {"name": name, "age": age}

URL: http://localhost:8000/hello/Ravi/20

{"name":"Ravi","age":"20"}

Path Parameters with Type Hints

@app.get("/hello/{name}/{age}")
async def hello(name: str, age: int):
    return {"name": name, "age": age}

URL: http://localhost:8000/hello/20/Ravi → Error because age must be an integer.

Query Parameters

Query parameters are sent in the URL after a ? using key-value pairs.

http://localhost:8000/hello?name=Ravi&age=20

FastAPI function:

@app.get("/hello")
async def hello(name: str, age: int):
    return {"name": name, "age": age}

Validation on Parameters

FastAPI allows validation on path and query parameters using the Path and Query classes.

Example: Validating a String Path Parameter

from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/hello/{name}")
async def hello(name: str = Path(..., min_length=3, max_length=10)):
    return {"name": name}

If name is shorter than 3 or longer than 10 characters, FastAPI returns:

{
  "detail": [
    {
      "type": "string_too_long",
      "loc": ["path", "name"],
      "msg": "String should have at most 10 characters",
      "input": "Tutorialspoint",
      "ctx": {"max_length": 10}
    }
  ]
}

Numeric Validation Example

from fastapi import FastAPI, Path

@app.get("/hello/{name}/{age}")
async def hello(
    *, 
    name: str = Path(..., min_length=3, max_length=10), 
    age: int = Path(..., ge=1, le=100)
):
    return {"name": name, "age": age}

URL: http://localhost:8000/hello/hi/110 → Validation error for both name and age.

Query Parameter Validation

from fastapi import FastAPI, Path, Query

@app.get("/hello/{name}/{age}")
async def hello(
    *, 
    name: str = Path(..., min_length=3, max_length=10), 
    age: int = Path(..., ge=1, le=100), 
    percent: float = Query(..., ge=0, le=100)
):
    return {"name": name, "age": age, "percent": percent}

URL: http://localhost:8000/hello/Ravi/20?percent=79

{"name": "Ravi", "age": 20, "percent": 79}

Conclusion

FastAPI makes it easy to:

  • Define path and query parameters
  • Apply type hints and validation rules
  • Return JSON responses automatically
  • Explore APIs interactively via OpenAPI (Swagger UI)

This ensures APIs are robust, easy to use, and self-documenting, making FastAPI ideal for modern web development.



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...