Skip to main content

FastAPI Extended Query Method

Native HTTP QUERY support for FastAPI.

Overview

FastAPIWithQueryHttpMethod extends FastAPI with native support for the HTTP QUERY method while preserving the FastAPI developer experience.

Installation

pip install fastapi-extended-query-method

Quick Start

## main.py

import uuid
from typing import List, Optional
import uvicorn
from fastapi import Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel

# 1. Initialize the app using your custom class
from fastapi_extended_query_method import FastAPIWithQueryHttpMethod

app = FastAPIWithQueryHttpMethod(query_saving_cache=True)

# 2. Mock Data for quick testing
MOCK_PRODUCTS = [
    {"id": 1, "name": "Gaming Laptop", "category": "electronics", "price": 1200.99},
    {"id": 2, "name": "Smartphone", "category": "electronics", "price": 599.99},
    {"id": 3, "name": "Bluetooth Headphones", "category": "electronics", "price": 79.90},
    {"id": 4, "name": "Espresso Machine", "category": "appliances", "price": 150.00},
    {"id": 5, "name": "Blender", "category": "appliances", "price": 45.50},
    {"id": 6, "name": "Office Chair", "category": "furniture", "price": 180.00},
]

# 3. Pydantic Schemas
from pydantic import BaseModel

# ---- [ES] MODELOS DE PYDANTIC (ENTRADA Y SALIDA) ----
# ---- [EN] PYDANTIC MODELS (INPUT AND OUTPUT) ----

class SearchFilters(BaseModel):
    """
    [ES] Modelo de entrada para los filtros de búsqueda de productos.
    [EN] Input model for product search filters.
    """
    categories: list[str] = []
    excluded_brands: list[str]  = []
    max_price: float = 10_000
    min_price: float = 100

class ProductFormat(BaseModel):
    """
    [ES] Modelo que define la estructura estándar de un producto.
    [EN] Model defining the standard structure of a product.
    """
    id: int
    name: str
    category: str
    price: float
    brand: str


class SearchResponse(BaseModel):
    """
    [ES] Modelo de salida para la respuesta de la búsqueda.
    [EN] Output model for the search response.
    """
    status: str
    total_found: int
    products: list[ProductFormat]

# 4. Filter function simulating database queries with mock data
def get_products_from_sqlite(filters: SearchFilters, limit: int, order_by: str):
    results = MOCK_PRODUCTS.copy()
    
    # Apply search filters if they are provided
    if filters.categories:
        results = [p for p in results if p["category"].lower() in [c.lower() for c in filters.categories]]

    if filters.min_price is not None:
        results = [p for p in results if p["price"] >= filters.min_price]
        
    if filters.max_price is not None:
        results = [p for p in results if p["price"] <= filters.max_price]
    
    # Sort results dynamically (defaults to "id")
    results = sorted(results, key=lambda x: x.get(order_by, x["id"]))
    
    # Apply limit
    return results[:limit]


# 5. Endpoint using your custom @app.query decorator
@app.query("/products/filter", response_model=SearchResponse)
async def filter_products(
    filters: SearchFilters,
    limit: int = Query(default=10, ge=1),
    order_by: str = "id",
):
    
    print("----------------------------------------------------")
    # Fetch and filter the mock data
    filtered_products = get_products_from_sqlite(
        filters=filters,
        limit=limit,
        order_by=order_by,
    )

    execution_id = str(uuid.uuid4())

    return JSONResponse(
        content={
            "status": "success",
            "execution_id": execution_id,
            "total_found": len(filtered_products),
            "products": filtered_products,
        },
        headers={
            "X-Execution-Id": execution_id,
        },
    )


# 6. Mostrar las rutas registradas
@app.on_event("startup")
async def show_routes():
    print("\n================== REGISTERED ROUTES ==================")

    for route in app.routes:
        methods = getattr(route, "methods", None)
        print(
            f"Path: {route.path}"
            f"\nMethods: {methods}"
            f"\nName: {route.name}"
            f"\nOperation ID: {getattr(route, 'operation_id', None)}"
            "\n------------------------------------------------------"
        )

# 7. Direct startup block
if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="127.0.0.1",
        port=8000,
        reload=True,
    )

Start Server

python main.py

Swagger compatibility

After starting the application:

http://localhost:8000/docs

OpenAPI and Swagger do not currently support the HTTP QUERY method.

For that reason this package automatically exposes QUERY endpoints as both:

  • QUERY
  • POST

Use the POST operation in Swagger only for interactive testing.

Real clients should invoke the QUERY method directly.

Swagger Interface

Cache

query_saving_cache=True allows caching.

query_saving_cache=False automatically adds:

  • Cache-Control: no-store
  • Pragma: no-cache
  • Expires: 0

Testing API

python validate_data/test_api_query_method.py

API Results

Testing Cache

Using Cache Stored

python validate_data/test_cache_comparison.py

Stored Cache

NO Using Cache Stored

Without Cache

License

MIT

Release files for fastapi-extended-query-method 0.0.33.213

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-extended-query-method 0.0.33.213
File Size Uploaded
fastapi_extended_query_method-0.0.33.213.tar.gz 6.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-extended-query-method 0.0.33.213
File Interpreter ABI Platform
fastapi_extended_query_method-0.0.33.213-py3-none-any.whl Python 3 none any Details

Total release size: 12.4 kB

Release files / fastapi_extended_query_method-0.0.33.213.tar.gz

Download URL fastapi_extended_query_method-0.0.33.213.tar.gz
Size 6.0 kB
Tags Source
SHA-256 checksum
How to use checksums
d14d3037fbbb39958302dcdeba30d32afea909310c6d57b678c8a370c37ed2ff
BLAKE2b-256 checksum
How to use checksums
289a3738bc38a23fed08a92a9a481e0320d0c11f545f91a568b1bc7d3767023f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.12

Release files / fastapi_extended_query_method-0.0.33.213-py3-none-any.whl

Download URL fastapi_extended_query_method-0.0.33.213-py3-none-any.whl
Size 6.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f8754e18e2f907509179d345bc41a50c71b9d97c85e6b482d370b377a4c8000e
BLAKE2b-256 checksum
How to use checksums
073b0f4fca81bf84054d8723f7fa88a299f8f15d434533da0880cfee999d9d26
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.12

Release history Release notifications | RSS feed

This release

0.0.33.213 This release

2 release files

0.0.33

2 release files

0.0.32

2 release files

0.0.31

2 release files

0.0.3

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page