RDFLib

7.6.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to create an RDF Graph, define namespaces, add triples using URIRef, BNode, and Literal, and serialize the graph to the Turtle format. It's a fundamental example of how to represent and manage RDF data programmatically.

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")

view raw JSON →