This toolkit provides type-safe Pydantic models for standard vocabularies and enables round-trip serialization to and from RDF formats.
Once stable, this package will be officially released and distributed through PyPI. Stay tuned for updates!
In the meantime, you can install the package locally by following these steps:
-
Clone the Repository:
First, clone the repository to your local machine:
git clone https://github.com/DataArtifex/rdf-toolkit.git cd rdf-toolkit -
Install the Package:
From the project's home directory, run the following command to install the package:
uv pip install -e .
If you want to use this package as a dependency in another project (via requirements.txt or pyproject.toml) without waiting for the PyPI release, you can use the following methods:
uv handles git dependencies and lock files securely and is the preferred tool for this project:
uv add git+https://github.com/DataArtifex/rdf-toolkit.gitIf you are using pip install --require-hashes (common in Docker environments), pip cannot verify hashes for Git repositories. You must use the GitHub archive URL instead:
dartfx-rdf @ https://github.com/DataArtifex/rdf-toolkit/archive/MAIN_OR_COMMIT.tar.gz#sha256=HASH
Example for a specific commit:
dartfx-rdf @ https://github.com/DataArtifex/rdf-toolkit/archive/8e6d67ae093eb9321a5d8865d04d833de62ec95c.tar.gz#sha256=445e186c5b158ceb42d1406a762c8c9b728648c76fa047209ac391d24dd34b38
- Find the Commit Hash: On the GitHub repository page, click on "Commits" or look at the short hash near the code. Copy the full 40-character SHA.
- Form the Archive URL: Use the format
https://github.com/DataArtifex/rdf-toolkit/archive/COMMIT_SHA.tar.gz. - Calculate the SHA256: If you need the hash for verification, run:
curl -L https://github.com/DataArtifex/rdf-toolkit/archive/COMMIT_SHA.tar.gz -o temp.tar.gz sha256sum temp.tar.gz
The toolkit ships with a lightweight integration that lets you decorate
Pydantic models with RDF metadata and convert them directly to and from
rdflib graphs. The integration is provided by the
dartfx.rdf.pydantic module.
from typing import Annotated
from rdflib import Namespace, URIRef
from dartfx.rdf.pydantic import RdfBaseModel, RdfProperty
EX = Namespace("https://example.com/ns/")
class Project(RdfBaseModel):
rdf_type = EX.Project
rdf_namespace = EX
rdf_prefixes = {"ex": EX}
id: str
name: Annotated[str, RdfProperty(EX.name)]
homepage: Annotated[str, RdfProperty(EX.homepage)]
project = Project(id="rdftoolkit", name="RDF Toolkit", homepage="https://example.com/toolkit")
turtle = project.to_rdf(format="turtle")
print(turtle)The RdfProperty metadata describes which predicate should be used for each
field. When rdf_namespace is supplied the toolkit automatically builds URIs
for identifiers that are not already absolute. The resulting RDF graph is a
standard rdflib.Graph instance, so you can serialise it to any format that
rdflib supports by switching the format argument.
The same annotations are used to parse RDF back into Pydantic models. When a
model specifies rdf_type the deserialiser will look for a matching subject
and populate the fields from the graph.
loaded = Project.from_rdf(turtle, format="turtle")
assert loaded == projectNested models and multi-valued properties are also supported. Declare lists of
annotated fields, or embed other RdfBaseModel subclasses, and the toolkit
will recursively serialise and deserialise them.
The toolkit provides several ways to handle URIs and specific XSD datatypes:
- Resource Identifiers: Use
rdflib.URIRefas a type hint for fields that should be serialized as RDF resources. - XSD Datatypes: Specify the
datatypeinRdfPropertyto force a literal value to a specific XSD type (e.g.,XSD.anyURI,XSD.integer). - Localized Strings: Use
LocalizedStrfor automatic handling of language tags. Input can be a plain string, aLangString, a dictionary language map, or a mixed list — the value is always stored as aLangStringListwith convenience query methods (has_language,get_by_language,count_by_lang,languages, etc.) and built-in(value, lang)deduplication. - Validation: Combine with Pydantic's built-in types like
AnyUrlfor strict input validation. - Multiple RDF Types: Specify multiple RDF types as a list or set in
rdf_type(e.g.,rdf_type = [SCHEMA.PropertyValue, CDI.InstanceVariable]). Unmodeled incoming types from graphs are automatically preserved on round-trip.
from typing import Annotated, Optional
from pydantic import AnyUrl
from rdflib import XSD, SCHEMA, SKOS, URIRef
from dartfx.rdf.pydantic import RdfBaseModel, RdfProperty, LocalizedStr, LangString
class WebResource(RdfBaseModel):
# Serialized as an RDF resource (URIRef)
see_also: Annotated[Optional[URIRef], RdfProperty(SCHEMA.seeAlso)] = None
# Validated by Pydantic, serialized as "..."^^xsd:anyURI literal
url: Annotated[AnyUrl, RdfProperty(SCHEMA.url, datatype=XSD.anyURI)]
class Concept(RdfBaseModel):
rdf_type = SKOS.Concept
rdf_namespace = EX
id: str
pref_label: Annotated[LocalizedStr | None, RdfProperty(SKOS.prefLabel)] = None
c = Concept(id="c1", pref_label={"en": "World", "es": "Mundo"})
c.pref_label.has_language("en") # True
c.pref_label.get_by_language("es") # LangStringList([LangString("Mundo","es")])
c.pref_label += LangString("Welt", "de") # add with dedup
str(c.pref_label) # str-like when one untagged entry existsSee the Pydantic RDF integration guide for a
deeper walk-through including the full LangStringList API, language-tagged
strings, custom datatypes and subject selection.
The toolkit provides Pydantic models for the following vocabularies:
- DCTERMS: Dublin Core Metadata Initiative Terms
- FOAF: Friend of a Friend
- ODRL: Open Digital Rights Language
- PROV: PROV Ontology
- SKOS: Simple Knowledge Organization System (including SKOS-XL)
- SPDX: Software Package Data Exchange
- VCARD: vCard / Virtual Contact File
- XKOS: Extended Knowledge Organization System
# Run all tests
uv run pytest tests/ -v
# Run only vocabulary tests
uv run pytest tests/test_vocabularies_*.py -v
# Run benchmarks only
uv run pytest tests/test_benchmarks_serialization.py --benchmark-only- Migrate model from Python @dataclass to Pydantic
- Explore transitioning into RDF annotation and serializer from DCAT SeMPyRO project
- RDF deserializer (from graph to Python)
- Peer testing and validation
- Expand vocabulary coverage
- Improve documentation
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature - Commit your changes:
git commit -am 'Add some feature' - Push to the branch:
git push origin my-new-feature - Submit a pull request :D