Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API endpoints implementation with FastAPI #4

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 81 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,84 @@ python version_manager.py
- Provides clear logging of version changes and database updates.

**Note**:
The version_manager.py script is designed to work in conjunction with the initial database population performed by initial_population.py. Ensure that you have run the initial population script before using the version manager.
The version_manager.py script is designed to work in conjunction with the initial database population performed by initial_population.py. Ensure that you have run the initial population script before using the version manager.

## APIs documentation

A server has been implemented based on FastAPI to allow users to interact with the database with "read only access". the API allows users to retrieve versions of a specified data model and obtain the schema URL for a particular version.

To start the server, run the following command:

```bash
cd api
python -m uvicorn server:app --reload
```

### API endpoints

**1. List Smart Data Model Versions**

This endpoint retrieves all the versions associated with a specified data model.

````
GET /datamodel/{name}/versions
````

**Parameters**

- name (path parameter): The name of the data model (Entity Type) for which you want to retrieve the versions (e.g., WaterObserved).

**Responses**

- 200 OK: Returns a list of version numbers for the specified data model.
feki-rihab marked this conversation as resolved.
Show resolved Hide resolved
- 404 Not Found: If no data model with the specified name exists in the database.

**Example request URL**

```shell
http://127.0.0.1:8000/datamodel/WaterObserved/versions'
```

**Example response**

````shell
[
"0.0.4",
"0.0.3",
"0.0.2",
"0.0.1"
]
````


**2. Get Schema URL by Version**

This endpoint retrieves the schema URL for a specific version of a given data model.
````
GET /datamodel/{name}/versions/{version}
````

**Parameters**

- name (path parameter): The name of the data model (Entity Type) for which you want to retrieve the versions (e.g., WeatherForecast).
- version (path parameter): The version number of the data model (e.g., 0.3.4).

**Responses**

- 200 OK: Returns a JSON object containing the version number and its corresponding schema URL.
feki-rihab marked this conversation as resolved.
Show resolved Hide resolved
- 404 Not Found: If the specified data model version does not exist in the database.

**Example request URL**

```
http://127.0.0.1:8000/datamodel/WaterObserved/versions/0.0.4
```

**Example response**

```shell
{
"version": "0.0.4",
"schemaUrl": "https://raw.githubusercontent.com/smart-data-models/dataModel.Environment/6735c895688276b924b64ab27c18547222c05219/WaterObserved/schema.json"
}
```
88 changes: 88 additions & 0 deletions api/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
##
# Copyright 2024 FIWARE Foundation, e.V.
#
# This file is part of SDM Quality Testing
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
##


from fastapi import FastAPI, HTTPException, status
from dotenv import dotenv_values
from pymongo import MongoClient
from contextlib import asynccontextmanager


config = dotenv_values(dotenv_path="../.env")


# Define a lifespan context manager
@asynccontextmanager
async def lifespan(app):
# Startup logic
app.mongodb_client = MongoClient(config["MONGO_URI"])
app.database = app.mongodb_client[config["DB_NAME"]]
print("Connected to the MongoDB database!")

# Yield control back to the application
yield

# Shutdown logic
app.mongodb_client.close()
print("Disconnected from the MongoDB database!")


app = FastAPI(lifespan=lifespan, title="SDM versions manager")

@app.get("/info")
async def root():
return {"message: This is the SDM version manager api."}


@app.get("/datamodel/{name}/versions", response_description="Get all the versions of a data model", status_code=status.HTTP_200_OK)
def list_datamodel_versions(name: str):
collection = app.database["versions"]

# Querying the database for all documents of the specified data model name
data_model_list = list(collection.find({"dataModel": name}))
if not data_model_list:
raise HTTPException(status_code=404, detail="Data model not found in the database")

# Extracting only the version numbers from the documents
versions = [model["version"] for model in data_model_list]

return versions


@app.get("/datamodel/{name}/versions/{version}", response_description="Get the schema URL of a data model at a particular version", status_code=status.HTTP_200_OK)
def get_schema(name: str, version: str):
collection = app.database["versions"]

# Querying the database for the specific data model and version
result = collection.find_one({"dataModel": name, "version": version})

if result is None:
raise HTTPException(status_code=404, detail="Data model version not found in the database")

# Prepare the response dictionary with version and schemaUrl
response_data = {
"version": result["version"],
"schemaUrl": result["schemaUrl"],
}

return response_data

1 change: 0 additions & 1 deletion main.py

This file was deleted.

2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
requests==2.32.3
pymongo==4.8.0
python-dotenv==1.0.1
fastapi==0.115.5
uvicorn==0.32.1
2 changes: 1 addition & 1 deletion sdm_versions_manager/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
["WaterQuality", "WaterQualityObserved"],
["WaterQuality", "WaterQualityPredicted"],
["WaterConsumption", "WaterConsumptionObserved"],
["SatelliteImagery", "EOSatelliteImagery "],
["SatelliteImagery", "EOSatelliteImagery"],
["CallComplaints", "Complaint"]
]
}
2 changes: 1 addition & 1 deletion sdm_versions_manager/version_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def fetch_latest_versions(data_model_list):
"subject": subject,
"dataModel": data_model,
"version": current_version,
"SchemaUrl": f"https://github.com/smart-data-models/dataModel.{subject}/blob/{commit_hash}/{data_model}/schema.json",
"schemaUrl": f"https://github.com/smart-data-models/dataModel.{subject}/blob/{commit_hash}/{data_model}/schema.json",
"commitHash": commit_hash,
"commitDate": commit_date
})
Expand Down