Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/dhanyasukumaran1/fhir_query_validator/llms.txt

Use this file to discover all available pages before exploring further.

FHIRQueryValidator gives you a structured way to check FHIR R4 REST API query strings before they reach a server. Instead of discovering malformed queries through HTTP errors at runtime, you validate them in your application code, collect structured error and warning messages, and decide how to proceed. This guide walks through creating a validator instance, inspecting results, and integrating validation into real application workflows.

Create a validator instance

Import FHIRQueryValidator and instantiate it once. The instance is reusable across requests and stores no per-query state.
from fhir_query_validator import FHIRQueryValidator

validator = FHIRQueryValidator()
Create a single FHIRQueryValidator instance at module or application level and reuse it. Constructing a new instance for every query wastes initialization overhead.

Validate a single query

Call validate_query() with a FHIR search query string. The string should include the resource type and all search parameters, formatted as you would append them to a FHIR base URL.
result = validator.validate_query("Patient?name=Smith&birthdate=1990-01-01")
validate_query() always returns a ValidationResult object—it never raises an exception for an invalid query. The result object tells you whether the query is valid and, if not, what is wrong.

Work with ValidationResult

is_valid

boolTrue when the query has no errors. Warnings may still be present.

errors

list[str] — Descriptions of every structural or semantic problem that makes the query invalid.

warnings

list[str] — Descriptions of issues that do not invalidate the query but may produce unexpected results.
result = validator.validate_query("Patient?birthdate=gt1990-01-01")

if result.is_valid:
    print("Query is valid")
else:
    print("Query is invalid:")
    for error in result.errors:
        print(f"  ERROR: {error}")

for warning in result.warnings:
    print(f"  WARNING: {warning}")

Format error messages for display

When surfacing validation feedback to users or logs, join errors and warnings into a single readable block:
def format_validation_result(result) -> str:
    lines = []
    if result.errors:
        lines.append("Errors:")
        lines.extend(f"  - {e}" for e in result.errors)
    if result.warnings:
        lines.append("Warnings:")
        lines.extend(f"  - {w}" for w in result.warnings)
    if not lines:
        return "Query is valid with no warnings."
    return "\n".join(lines)

result = validator.validate_query("Patient?unknown_param=foo")
print(format_validation_result(result))

Integrate validation into a query-building function

A common pattern is to validate a query immediately after constructing it and raise a descriptive error before dispatching it to a FHIR server:
from fhir_query_validator import FHIRQueryValidator

validator = FHIRQueryValidator()


def build_patient_query(name: str, birthdate: str) -> str:
    query = f"Patient?name={name}&birthdate={birthdate}"
    result = validator.validate_query(query)

    if not result.is_valid:
        errors = "; ".join(result.errors)
        raise ValueError(f"Invalid FHIR query '{query}': {errors}")

    return query


# Raises ValueError if the constructed query is invalid
query = build_patient_query("Smith", "1990-01-01")
This pattern is most useful when query parameters come from user input or configuration. If you build static queries at development time, prefer catching errors in tests rather than in production error paths.

Validate a batch of queries

When you need to validate multiple queries at once—for example, during a startup check or a test suite—use validate_batch(). It accepts a list of query strings and returns a list of ValidationResult objects in the same order.
queries = [
    "Patient?name=Smith",
    "Observation?code=8302-2",
    "Encounter?badparam=x",
    "MedicationRequest?status=active",
]

results = validator.validate_batch(queries)

for query, result in zip(queries, results):
    status = "OK" if result.is_valid else "INVALID"
    print(f"[{status}] {query}")
    for error in result.errors:
        print(f"         ERROR: {error}")
validate_batch() is more efficient than calling validate_query() in a loop when validating a large set of queries, because the validator can share internal setup work across the batch.

Explore supported resources and parameters

FHIRQueryValidator exposes the complete list of FHIR R4 resources and search parameters it understands. Use these to programmatically check whether a resource or parameter is supported before constructing a query.
validator = FHIRQueryValidator()

print(validator.supported_resources)
# ['Account', 'ActivityDefinition', 'AdverseEvent', ..., 'Patient', ..., 'ValueSet']

if "Observation" in validator.supported_resources:
    print("Observation queries are supported")

Real-world example: validate before sending to a FHIR server

The following example shows a complete integration: build a query, validate it, log any warnings, and only proceed to the HTTP request if the query is valid.
import logging
import requests
from fhir_query_validator import FHIRQueryValidator

logger = logging.getLogger(__name__)
validator = FHIRQueryValidator()

FHIR_BASE_URL = "https://your-fhir-server.example.com/fhir"


def fetch_observations(patient_id: str, code: str):
    query = f"Observation?patient={patient_id}&code={code}&_sort=-date&_count=10"
    result = validator.validate_query(query)

    if not result.is_valid:
        for error in result.errors:
            logger.error("FHIR query validation error: %s | query=%s", error, query)
        raise ValueError(f"Query failed validation: {query}")

    for warning in result.warnings:
        logger.warning("FHIR query validation warning: %s | query=%s", warning, query)

    response = requests.get(f"{FHIR_BASE_URL}/{query}")
    response.raise_for_status()
    return response.json()
1

Build the query string

Construct the full FHIR search query, including resource type and all parameters.
2

Validate before sending

Call validate_query() and check result.is_valid. Never send an invalid query to the server.
3

Log warnings

Even when is_valid is True, log any result.warnings so you can catch queries that might return unexpected results.
4

Dispatch the request

Only send the HTTP request after validation passes.
Skipping validation for “known good” queries can mask problems when query parameters are constructed from dynamic inputs. Validate every query that includes user-supplied or configuration-derived values.

Build docs developers (and LLMs) love