Skip to content

Running a Sample

Julio Cesar edited this page Jan 28, 2026 · 5 revisions

4.1 - Temperature Conversion Sample

  • The sample below represent a self-contained SQLite database with some sample data from temperature and relative humidity, a business model to convert temperature from Celsius to Fahrenheit, also data can be passed via endpoint parameters to be converted by the example business model.

For simplification the following files can be found under the following repo folder: https://github.com/JCGCosta/OntologyToAPI/tree/master/example

  • Ontology file with triples to a weather use case extending the OntologyToAPI framework:
# ./metadata_example.ttl

@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl:  <http://www.w3.org/2002/07/owl#> .

@prefix md:  <http://www.cedri.com/OntologyToAPI-Metadata#> .
@prefix comm:  <http://www.cedri.com/OntologyToAPI-Communications#> .

@prefix ex:   <http://example.org/> .

# Class Definitions

ex:Temperature_C rdf:type owl:Class ;
          rdfs:subClassOf md:Metadata ;
          rdfs:comment "A measure of the average kinetic energy of the particles within a substance, which corresponds to its hotness or coldness." .

ex:Relative_Humidity rdf:type owl:Class ;
          rdfs:subClassOf md:Metadata ;
          rdfs:comment "The ratio of the amount of water vapor currently in the air to the maximum amount the air could hold at that specific temperature, expressed as a percentage." .

# Individuals for Metadata and Communication

ex:SQLITE_DB rdf:type owl:NamedIndividual ,
                      comm:DatabaseCommunication ;
             comm:hasConnectionString "sqlite+aiosqlite:///example.db" ;
             comm:usesTechnology "SQLITE" .

ex:Temperature_C_Source rdf:type owl:NamedIndividual ,
                      md:Source ;
             md:hasCommunicationTechnology ex:SQLITE_DB ;
             md:hasDescription "Retrieves the temperature data from a local SQLite database." ;
             md:hasQuery "SELECT temperature_c FROM weather;" .

ex:Temperature_C_MD rdf:type owl:NamedIndividual ,
                           ex:Temperature_C ;
                  md:hasSource ex:Temperature_C_Source ;
                  md:hasType "float" .

ex:Relative_Humidity_Source rdf:type owl:NamedIndividual ,
                      md:Source ;
             md:hasCommunicationTechnology ex:SQLITE_DB ;
             md:hasDescription "Retrieves the relative humidity data from a local SQLite database." ;
             md:hasQuery "SELECT r_humidity FROM weather;" .

ex:Relative_Humidity_MD rdf:type owl:NamedIndividual ,
                           ex:Relative_Humidity ;
                  md:hasSource ex:Relative_Humidity_Source ;
                  md:hasType "float" .
  • Ontology file with triples to represent temperature convertion sample in the OntologyToAPI framework:
# ./bm_example.ttl

@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl:  <http://www.w3.org/2002/07/owl#> .

@prefix md:  <http://www.cedri.com/OntologyToAPI-Metadata#> .
@prefix comm:  <http://www.cedri.com/OntologyToAPI-Communications#> .
@prefix bm:  <http://www.cedri.com/OntologyToAPI-BusinessModel#> .
@prefix excode:  <http://www.cedri.com/OntologyToAPI-ExternalCode#> .

@prefix ex:   <http://example.org/> .

# Class Definitions

ex:CelsiusToFahrenheitBM rdf:type owl:Class ;
                       rdfs:subClassOf bm:BusinessModel ;
                       rdfs:comment "This business model allows the convertion from Celsius to Fahrenheit." .

# Individuals for Business Models

ex:CelsiusToFahrenheit.py rdf:type owl:NamedIndividual ,
                                   excode:ExternalCode ;
                          excode:hasFunction "convert_temperature_c_to_f" ;
                          excode:hasPythonFile "bm.py" ;
                          excode:requiresLib "requests" .

ex:Temperature_P rdf:type owl:NamedIndividual ,
                          bm:Parameter ;
                 bm:hasParameterLabel "temperature_c" ;
                 bm:hasParameterType "float" .

ex:CelsiusToFahrenheit rdf:type owl:NamedIndividual ,
                                ex:CelsiusToFahrenheitBM ;
                         bm:requiresMetadata ex:Temperature_C_MD;
                         bm:hasExternalCode ex:CelsiusToFahrenheit.py ;
                         bm:hasParameter ex:Temperature_P .
  • Code to have the business model implementation:
# ./bm.py

async def convert_temperature_c_to_f(data):
    if not data.metadata and data.params["temperature_c"] is None:
        return {"error": "No temperature was provided from Metadata or from the endpoint Parameters."}
    if data.params["temperature_c"] is not None:
        return {
            "original": data.params["temperature_c"],
            "converted": data.params["temperature_c"] * 9 / 5 + 32
        }
    else:
        return {
            "original": [t["temperature_c"] for t in data.metadata["Temperature_C_MD"]],
            "converted": [t["temperature_c"] * 9 / 5 + 32 for t in data.metadata["Temperature_C_MD"]]
        }
  • Code to generate the API:
# ./main.py

import uvicorn
import sqlite3
from pathlib import Path
from OntologyToAPI.core.APIGenerator import APIGenerator

def configuring_a_sample_sqlite_database():
    if not Path('example.db').exists():
        with sqlite3.connect('example.db') as conn:
            cursor = conn.cursor()
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS weather (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    temperature_c FLOAT NOT NULL,
                    r_humidity FLOAT NOT NULL
                );
            ''')
            cursor.execute("INSERT INTO weather (temperature_c, r_humidity) VALUES ('21.5', '60');")
            cursor.execute("INSERT INTO weather (temperature_c, r_humidity) VALUES ('22.0', '58');")
            cursor.execute("INSERT INTO weather (temperature_c, r_humidity) VALUES ('20.8', '65');")
            conn.commit()

if __name__ == "__main__":
    configuring_a_sample_sqlite_database()
    APIGen = APIGenerator(showLogs=True)
    APIGen.load_ontologies(paths=[
        "metadata_example.ttl",
        "bm_example.ttl"
    ])
    APIGen.serialize_ontologies()
    api_app = APIGen.generate_api_routes()
    uvicorn.run(api_app, host="127.0.0.1", port=5000)
  • Your project structure should look something like this:
├── metadata_example.ttl
├── bm_example.ttl
├── bm.py
├── main.py
  • Then you should be able to run the example as follows:
# To run the example, then execute:
python main.py

# You can access the API documentation at: http://localhost:5000

Clone this wiki locally