RDFLib
RDFLib is a Python library for working with RDF (Resource Description Framework), a simple yet powerful language for representing information. It provides a Graph data structure, parsers and serializers for various RDF formats (e.g., Turtle, N-Triples, RDF/XML, JSON-LD), and SPARQL query capabilities. RDFLib is actively maintained with frequent minor releases and major versions typically every 1-2 years.
Warnings
- breaking The handling of the `publicID` parameter in `Graph.parse` and `Dataset.parse` methods changed in version 7.0.0. It now explicitly sets the base URI for parsing, potentially altering how relative URIs are resolved in some cases.
- deprecated Several methods and attributes of the `Dataset` class have been deprecated in version 7.3.0 and are scheduled for removal in the next major release (likely 8.0.0). This aims to improve consistency and align `Dataset` more closely with RDF specifications.
- gotcha Many parsers, serializers, and advanced features (e.g., SPARQL, JSON-LD, HTML5 parsing, specific datatype handling) rely on optional dependencies that are not installed by default. Without them, you might encounter `ImportError` or incomplete functionality.
- gotcha Python 3.8 support was temporarily removed in version 7.1.2 and then re-added in 7.1.3 due to a typing-related regression. Users on specific patch versions of 7.1.x might experience unexpected behavior or installation issues on Python 3.8.
Install
-
pip install rdflib -
pip install "rdflib[json-ld,sparql,rdf4j,graphdb]"
Imports
- Graph
from rdflib import Graph
- Namespace
from rdflib import Namespace
- URIRef
from rdflib import URIRef
- BNode
from rdflib import BNode
- Literal
from rdflib import Literal
- FOAF
from rdflib.namespace import FOAF
Quickstart
from rdflib import Graph, Literal, Namespace, URIRef
from rdflib.namespace import FOAF, XSD
# Create a Graph
g = Graph()
# Define a custom namespace
EX = Namespace("http://example.org/people/")
# Create URIs for resources
john = EX.johnDoe
jane = EX.janeDoe
# Add triples to the graph
g.add((john, FOAF.name, Literal("John Doe")))
g.add((john, FOAF.mbox, URIRef("mailto:john.doe@example.org")))
g.add((john, FOAF.age, Literal(30, datatype=XSD.integer)))
g.add((jane, FOAF.name, Literal("Jane Doe")))
g.add((jane, FOAF.age, Literal(25, datatype=XSD.integer)))
# Serialize the graph to Turtle format and print it
print(g.serialize(format="turtle"))
# You can also parse from a file or string
# g.parse("path/to/my_data.ttl", format="turtle")