rdf_core library

RDF (Resource Description Framework) Library for Dart

This library provides a comprehensive implementation of the W3C RDF data model, allowing applications to parse, manipulate, and serialize RDF data in various ways.

It implements the RDF 1.1 Concepts and Abstract Syntax specification and supports multiple serialization formats.

Core Concepts

RDF Data Model

RDF (Resource Description Framework) represents information as a graph of statements called "triples". Each triple consists of three parts:

  • Subject: The resource being described (an IRI or blank node)
  • Predicate: The property or relationship type (always an IRI)
  • Object: The property value or related resource (an IRI, blank node, or literal)

Key Components

  • IRIs: Internationalized Resource Identifiers that uniquely identify resources
  • Blank Nodes: Anonymous resources without global identifiers
  • Literals: Values like strings, numbers, or dates (optionally with language tags or datatypes)
  • Triples: Individual statements in the form subject-predicate-object
  • Graphs: Collections of triples representing related statements
  • Quads: Triples with an additional graph context component
  • Datasets: Collections containing a default graph and zero or more named graphs

Serialization Codecs

This library supports these RDF serialization codecs:

For RDF Graphs:

  • Turtle: A compact, human-friendly text format (MIME type: text/turtle)
  • JSON-LD: JSON-based serialization of Linked Data (MIME type: application/ld+json)
  • N-Triples: A line-based, plain text format for encoding RDF graphs (MIME type: application/n-triples)

For RDF Datasets:

  • N-Quads: A line-based format for RDF datasets with named graph support (MIME type: application/n-quads)

The library uses a plugin system to allow registration of additional codecs.

Usage Examples

Basic Decoding and Encoding

// Create an RDF library instance with standard formats
final rdf = RdfCore.withStandardCodecs();

// Decode Turtle data
final turtleData = '''
@prefix foaf: <http://xmlns.com/foaf/0.1/> .

<http://example.org/john> foaf:name "John Smith" ;
                           foaf:knows <http://example.org/jane> .
''';

final graph = rdf.decode(turtleData, contentType: 'text/turtle');

// Encode to JSON-LD
final jsonLd = rdf.encode(graph, contentType: 'application/ld+json');
print(jsonLd);

Creating and Manipulating Graphs

// Create an empty graph
final graph = RdfGraph();

// Create terms
final subject = const IriTerm('http://example.org/john');
final predicate = const IriTerm('http://xmlns.com/foaf/0.1/name');
final object = LiteralTerm.string('John Smith');

// Add a triple
final newGraph = graph.withTriple(Triple(subject, predicate, object));

// Query the graph
final nameTriples = graph.getObjects(
  subject,
  predicate
);

// Print all objects for the given subject and predicate
for (final triple in nameTriples) {
  print('Name: ${triple.object}');
}

Working with RDF Datasets

// Create quads with graph context
final alice = IriTerm('http://example.org/alice');
final bob = IriTerm('http://example.org/bob');
final foafName = IriTerm('http://xmlns.com/foaf/0.1/name');
final foafKnows = IriTerm('http://xmlns.com/foaf/0.1/knows');
final peopleGraph = IriTerm('http://example.org/graphs/people');

final quads = [
  Quad(alice, foafName, LiteralTerm.string('Alice')), // default graph
  Quad(alice, foafKnows, bob, peopleGraph), // named graph
];

// Create dataset from quads
final dataset = RdfDataset.fromQuads(quads);

// Encode dataset to N-Quads format
final nquadsData = rdf.encodeDataset(dataset, contentType: 'application/n-quads');

// Decode N-Quads data
final decodedDataset = rdf.decodeDataset(nquadsData, contentType: 'application/n-quads');

Auto-detection of codecs

// The library can automatically detect the codec from content
final unknownContent = getContentFromSomewhere();
final graph = rdf.decode(unknownContent); // Format auto-detected

Using Custom Prefixes in Serialization

Note that this is rarely needed, as the library knows some well-known prefixes and will automatically generate missing prefixes for you. However, this gives you more control over the output.

final customPrefixes = {
  'example': 'http://example.org/',
  'foaf': 'http://xmlns.com/foaf/0.1/'
};

final turtle = rdf.encode(
  graph,
  contentType: 'text/turtle',
  options: TurtleEncoderOptions(
    customPrefixes: customPrefixes
  )
);

Architecture

The library follows a modular design with these key components:

  • Terms: Classes for representing RDF terms (IRIs, blank nodes, literals)
  • Triples: The atomic data unit in RDF, combining subject, predicate, and object
  • Graphs: Collections of triples with query capabilities
  • Decoders: Convert serialized RDF text into graph structures
  • Encoders: Convert graph structures into serialized text
  • Codec Registry: Plugin system for registering new codecs

The design follows IoC principles with dependency injection, making the library highly testable and extensible.

Classes

BaseRdfCodecRegistry<G>
BlankNodeTerm
BlankNode (anonymous resource) in RDF
CompactIri
FullIri
IriCompaction
Utility class for analyzing RDF graphs and generating namespace prefixes.
IriCompactionResult
IriCompactionSettings
IriRelativizationOptions
Configuration options for IRI relativization behavior.
IriTerm
IRI (Internationalized Resource Identifier) in RDF
JsonLdDecoder
Decoder for JSON-LD format
JsonLdDecoderOptions
Configuration options for JSON-LD decoding
JsonLdEncoder
Encoder for converting RDF graphs to JSON-LD format.
JsonLdEncoderOptions
Configuration options for JSON-LD encoding
JsonLdGraphCodec
RDF Format implementation for the JSON-LD serialization format.
LiteralTerm
Literal value in RDF
NQuadsCodec
Format definition for the N-Quads RDF serialization format.
NQuadsDecoder
Decoder for the N-Quads format.
NQuadsDecoderOptions
Options for configuring the N-Quads decoder behavior.
NQuadsEncoder
Encoder for the N-Quads format.
NQuadsEncoderOptions
Options for configuring the N-Quads encoder behavior.
NTriplesCodec
Format definition for the N-Triples RDF serialization format.
NTriplesDecoder
Decoder for the N-Triples format.
NTriplesDecoderOptions
Options for configuring the N-Triples decoder behavior.
NTriplesEncoder
Encoder for the N-Triples format.
NTriplesEncoderOptions
Options for configuring the N-Triples encoder behavior.
PrefixedIri
Quad
Represents an immutable RDF quad with graph context
RdfCodec<G>
RdfCodecRegistry
Manages registration and discovery of RDF codec plugins.
RdfCore
RDF Core Library
RdfDataset
Represents an immutable RDF dataset containing a default graph and named graphs
RdfDatasetCodec
Represents a dataset codec that can be handled by the RDF framework.
RdfDatasetCodecRegistry
Manages registration and discovery of RDF dataset codec plugins.
RdfDecoder<G>
Base class for decoding RDF documents in various serialization formats
RdfEncoder<G>
Interface for encoding RDF data structures to different serialization formats.
RdfGraph
Represents an immutable RDF graph with triple pattern matching capabilities
RdfGraphCodec
Represents a content codec that can be handled by the RDF framework.
RdfGraphDecoder
Base class for decoding RDF documents in various serialization formats
RdfGraphDecoderOptions
Configuration options for RDF graph decoders
RdfGraphEncoder
Interface for encoding RDF graphs to different serialization formats.
RdfGraphEncoderOptions
Configuration options for RDF graph encoders.
RdfGraphName
RdfNamedGraph
Represents an immutable named graph in an RDF dataset
RdfNamespaceMappings
A class that provides access to RDF namespace mappings with support for custom mappings.
RdfObject
Base type for values that can appear in the object position of a triple
RdfPredicate
Base type for values that can appear in the predicate position of a triple
RdfSubject
Base type for values that can appear in the subject position of a triple
RdfTerm
Base type for all RDF terms
RelativeIri
SourceLocation
Contains information about source location where an error occurred
SpecialIri
Triple
Represents an RDF triple.
TurtleCodec
RDF Codec implementation for the Turtle serialization format.
TurtleDecoder
Decoder for Turtle format RDF documents
TurtleDecoderOptions
Configuration options for the Turtle decoder
TurtleEncoder
Encoder for serializing RDF graphs to Turtle syntax.
TurtleEncoderOptions
Configuration options for Turtle serialization.

Enums

IriCompactionType
IriRole
TraversalDecision
Decision for traversal control during subgraph extraction
TurtleParsingFlag
Flags for non-standard Turtle parsing behavior.

Properties

allowedCompactionTypesAll Map<IriRole, Set<IriCompactionType>>
final
jsonldGraph JsonLdGraphCodec
Global convenience variable for working with JSON-LD format
final
nquads NQuadsCodec
Global convenience variable for working with N-Quads format
final
ntriples NTriplesCodec
Global convenience variable for working with N-Triples format
final
rdf RdfCore
Global convenience variable for accessing RDF functionality with standard codecs pre-registered
final
turtle TurtleCodec
Global convenience variable for working with Turtle format
final

Typedefs

AllowedCompactionTypes = Map<IriRole, Set<IriCompactionType>>
IriFilter = bool Function(IriTerm iri, {required IriRole role})
Function type for filtering IRIs that should be considered for prefix generation.
IriTermFactory = IriTerm Function(String iri)
TraversalFilter = TraversalDecision Function(Triple triple, int depth)
Function type for controlling subgraph traversal

Exceptions / Errors

CodecNotSupportedException
Exception thrown when an attempt is made to use an unsupported codec
RdfConstraintViolationException
Exception thrown when an RDF model constraint is violated
RdfCyclicGraphException
Exception thrown when the graph contains cycles that prevent encoding
RdfDecoderException
Base exception class for all RDF decoder-related errors
RdfEncoderException
Base exception class for all RDF encoding-related errors
RdfException
Base exception class for all RDF-related errors.
RdfInvalidIriException
Exception thrown when the decoder encounters an invalid IRI
RdfShapeValidationException
Exception thrown when an RDF graph doesn't conform to a specified shape
RdfSyntaxException
Exception thrown when the decoder encounters syntax errors in the input
RdfTypeException
Exception thrown when there's a type error in RDF data
RdfUnsupportedEncoderFeatureException
Exception thrown when the encoder cannot represent a feature in the target format
RdfUnsupportedFeatureException
Exception thrown when the decoder encounters an unsupported feature
RdfValidationException
Base exception class for all RDF validation-related errors