Skip to main content

A SPARQL endpoint to serve local RDF files, machine learning models, or any other logic implemented in Python, using RDFLib and FastAPI.

Project description

✨ SPARQL endpoint for RDFLib

Version Python versions

Run tests Publish to PyPI CodeQL Coverage

rdflib-endpoint is a SPARQL endpoint based on RDFLib to easily serve RDF files, machine learning models, or any other logic implemented in Python via custom SPARQL functions.

It aims to enable python developers to easily deploy functions that can be queried in a federated fashion using SPARQL. For example: using a python function to resolve labels for specific identifiers, or run a classifier given entities retrieved using a SERVICE query to another SPARQL endpoint.

Feel free to create an issue, or send a pull request if you are facing issues or would like to see a feature implemented.

🧑‍🏫 How it works

The user defines and registers custom SPARQL functions using Python, and/or populate the RDFLib Graph, then the endpoint is started using uvicorn.

The deployed SPARQL endpoint can be used as a SERVICE in a federated SPARQL query from regular triplestores SPARQL endpoints. Tested on OpenLink Virtuoso (Jena based) and Ontotext GraphDB (rdf4j based). The endpoint is CORS enabled by default.

rdflib-endpoint can also be used directly from the terminal to quickly serve a RDF file as a SPARQL endpoint.

Built with RDFLib and FastAPI. Tested for Python 3.7, 3.8 and 3.9

📥 Install the package

Install the package from PyPI:

pip install rdflib-endpoint

⚡️ Quickly serve RDF files via a SPARQL endpoint

Use rdflib-endpoint as a command line interface (CLI) in your terminal to quickly serve one or multiple RDF files as a SPARQL endpoint, with YASGUI interface available on http://0.0.0.0:8000

You can use wildcard and provide multiple files, for example to serve all turtle, JSON-LD and nquads files in the current folder:

rdflib-endpoint serve *.ttl *.jsonld *.nq

🐍 SPARQL endpoint with custom functions

Checkout the example folder for a complete working app example to get started, including a docker deployment. A good way to create a new SPARQL endpoint is to copy this example folder, and start from it.

📝 Define custom SPARQL functions

This option makes it easier to define functions in your SPARQL endpoint, e.g. BIND(myfunction:custom_concat("start", "end") AS ?concat)

Create a app/main.py file in your project folder with your custom SPARQL functions, and endpoint parameters:

from rdflib_endpoint import SparqlEndpoint
import rdflib
from rdflib.plugins.sparql.evalutils import _eval

def custom_concat(query_results, ctx, part, eval_part):
    """Concat 2 strings in the 2 senses and return the length as additional Length variable
    """
    # Retrieve the 2 input arguments
    argument1 = str(_eval(part.expr.expr[0], eval_part.forget(ctx, _except=part.expr._vars)))
    argument2 = str(_eval(part.expr.expr[1], eval_part.forget(ctx, _except=part.expr._vars)))
    evaluation = []
    scores = []
    # Prepare the 2 result string, 1 for eval, 1 for scores
    evaluation.append(argument1 + argument2)
    evaluation.append(argument2 + argument1)
    scores.append(len(argument1 + argument2))
    scores.append(len(argument2 + argument1))
    # Append the results for our custom function
    for i, result in enumerate(evaluation):
        query_results.append(eval_part.merge({
            part.var: rdflib.Literal(result),
            # With an additional custom var for the length
            rdflib.term.Variable(part.var + 'Length'): rdflib.Literal(scores[i])
        }))
    return query_results, ctx, part, eval_part

# Start the SPARQL endpoint based on a RDFLib Graph and register your custom functions
g = rdflib.graph.ConjunctiveGraph()
app = SparqlEndpoint(
    graph=g,
    # Register the functions:
    functions={
        'https://w3id.org/um/sparql-functions/custom_concat': custom_concat
    },
    cors_enabled=True,
    # Metadata used for the SPARQL service description and Swagger UI:
    title="SPARQL endpoint for RDFLib graph", 
    description="A SPARQL endpoint to serve machine learning models, or any other logic implemented in Python. \n[Source code](https://github.com/vemonet/rdflib-endpoint)",
    version="0.1.0",
    public_url='https://your-endpoint-url/sparql',
    # Example queries displayed in the Swagger UI to help users try your function
    example_query="""Example query:\n
```
PREFIX myfunctions: <https://w3id.org/um/sparql-functions/>
SELECT ?concat ?concatLength WHERE {
    BIND("First" AS ?first)
    BIND(myfunctions:custom_concat(?first, "last") AS ?concat)
}
```"""
)

📝 Or directly define the custom evaluation

You can also directly provide the custom evaluation function, this will override the functions.

Refer to the RDFLib documentation to define the custom evaluation function. Then provide it when instantiating the SPARQL endpoint:

import rdflib
from rdflib.plugins.sparql.evaluate import evalBGP
from rdflib.namespace import FOAF, RDF, RDFS

def customEval(ctx, part):
    """Rewrite triple patterns to get super-classes"""
    if part.name == "BGP":
        # rewrite triples
        triples = []
        for t in part.triples:
            if t[1] == RDF.type:
                bnode = rdflib.BNode()
                triples.append((t[0], t[1], bnode))
                triples.append((bnode, RDFS.subClassOf, t[2]))
            else:
                triples.append(t)
        # delegate to normal evalBGP
        return evalBGP(ctx, triples)
    raise NotImplementedError()

app = SparqlEndpoint(
    graph=g,
    custom_eval=customEval
)

🦄 Run the SPARQL endpoint

You can then run the SPARQL endpoint server from the example folder on http://localhost:8000/sparql with uvicorn

cd example
uvicorn main:app --app-dir app --reload

You can access the YASGUI interface to easily query the SPARQL endpoint on http://localhost:8000

Checkout in the example/README.md for more details, such as deploying it with docker.

🧑‍💻 Development

📥 Install for development

Install from the latest GitHub commit to make sure you have the latest updates:

pip install rdflib-endpoint@git+https://github.com/vemonet/rdflib-endpoint@main

Or clone and install locally for development:

git clone https://github.com/vemonet/rdflib-endpoint
cd rdflib-endpoint
pip install -e .

You can use a virtual environment to avoid conflicts:

# Create the virtual environment folder in your workspace
python3 -m venv .venv
# Activate it using a script in the created folder
source .venv/bin/activate

✅️ Run the tests

Install additional dependencies for testing:

pip install pytest requests

Run the tests locally (from the root folder) and display prints:

pytest -s

📂 Projects using rdflib-endpoint

Here are some projects using rdflib-endpoint to deploy custom SPARQL endpoints with python:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rdflib-endpoint-0.1.5.tar.gz (13.5 kB view details)

Uploaded Source

Built Distribution

rdflib_endpoint-0.1.5-py3-none-any.whl (14.3 kB view details)

Uploaded Python 3

File details

Details for the file rdflib-endpoint-0.1.5.tar.gz.

File metadata

  • Download URL: rdflib-endpoint-0.1.5.tar.gz
  • Upload date:
  • Size: 13.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for rdflib-endpoint-0.1.5.tar.gz
Algorithm Hash digest
SHA256 27a6f788aa8f66d4f47de9061c6828ed707431cff674cb35c2ed7218972b424c
MD5 2e4d154e1eb61cbe0b9ea9e30000ae0e
BLAKE2b-256 27e61d0b06fc09ab77f89460519760b8f43de75ecfd4ba375936c47947994045

See more details on using hashes here.

File details

Details for the file rdflib_endpoint-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: rdflib_endpoint-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 14.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.9

File hashes

Hashes for rdflib_endpoint-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 0d4d74d9a5af8bfd76ab9cf93fe5a64fb4da6a577fefad7d17efceaac5dd030b
MD5 ea9695548a8c2977903b725ca55e85e9
BLAKE2b-256 f662e1cf5e0364d66c7daab86d3b070bf5c91fa08e646c2a0d893f54036727cc

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page