Getting started

A minimal path from install to your first query. For installation options and extras see Installation.

Install

pip install sparqlmodel

Define models

from sparqlmodel import Field, IRI, Relationship, SPARQLModel, SPARQLSession

class Organization(SPARQLModel):
    rdf_type = "schema:Organization"
    __prefixes__ = {"schema": "https://schema.org/"}

    id: IRI
    name: str = Field("schema:name")

class Person(SPARQLModel):
    rdf_type = "schema:Person"
    __prefixes__ = {"schema": "https://schema.org/"}

    id: IRI
    name: str = Field("schema:name")
    works_for: Organization | None = Relationship(
        "schema:worksFor", model=Organization
    )

Note

SPARQLModel subclasses Pydantic v2 BaseModel. Invalid field types fail at construction (ValidationError) before session.put. See Models and Pydantic validation for constraints, load-time validation, and the validation stack.

Persist and query

acme = Organization(id=IRI("urn:org:acme"), name="Acme Corp")
odos = Person(id=IRI("urn:person:odos"), name="Odos", works_for=acme)

with SPARQLSession() as session:
    session.put(odos)

    found = session.query(Person).where(Person.name == "Odos").first()
    team = session.query(Person).where(Person.works_for.name == "Acme Corp").all()
    full = session.get(Person, odos.id, depth=1)

Important

Use put() for upserts (cascade + orphan cleanup). Use add() only when you will not overwrite existing subject data.

What’s next

Guide

Topics

Models and Pydantic validation

Pydantic validation, Field kwargs, read vs write

Sessions and stores

Flush queue, stores, identity map, composition

Query DSL

Boolean filters, !=, limits, raw SPARQL

Real-world examples

Nobel, DCAT, Wikidata, Schema.org over bundled linked data

Topic

Document

Full ORM concepts

SparqlModel ORM guide

HttpStore / deployment

SparqlModel production guide

FastAPI

FastAPI integration

Async (asyncio)

FastAPI integrationAsyncSPARQLSession, AsyncHttpStore (same [http] extra)

Python API

API reference

Problems

Troubleshooting