Skip to content

Commit 39d5d48

Browse files
mbatsAxelRICHARD
authored andcommitted
[doc] Contribute API cookbook recipes in Python
Signed-off-by: Mélanie Bats <melanie.bats@obeo.fr>
1 parent 5245006 commit 39d5d48

23 files changed

+714
-158
lines changed

doc/content/modules/ROOT/pages/integration.adoc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ a|image::tap_app.svg[xref=user-manual:key-features.adoc]
1818

1919
Standard APIs support for seamless connections.
2020

21-
xref:user-manual:integration/api.adoc[Delve into]
21+
xref:developer-guide:api.adoc[Delve into]
2222

2323
a|image::globe.svg[xref=user-manual:what-is.adoc]
2424

doc/content/modules/user-manual/assets/attachments/sirius-web-openapi.json renamed to doc/content/modules/developer-guide/assets/attachments/sirius-web-openapi.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# These examples are adapted from the SysML v2 API Cookbook, available at
2+
# https://github.com/Systems-Modeling/SysML-v2-API-Cookbook, maintained by the
3+
# Object Management Group (OMG).
4+
# The original cookbook is designed for use with Jupyter Lab.
5+
# These examples have been adapted to run as standalone Python scripts, making
6+
# them suitable for use in various environments, including SysON.
7+
# They showcase practical usage scenarios and may include additional functionality
8+
# or modifications tailored to specific needs.
9+
10+
import requests # <1>
11+
from init_api import init_sysmlv2_api
12+
from fetch_projects import fetch_projects
13+
from datetime import datetime
14+
15+
def create_project(host, project_name): # <2>
16+
# Define project data as query parameters
17+
project_params = {
18+
"name": project_name
19+
}
20+
21+
# API endpoint to create a project
22+
url = f"{host}/projects" # <3>
23+
24+
# Send POST request with query parameters
25+
response = requests.post(url, params=project_params) # <4>
26+
27+
# Check if the project creation was successful
28+
if response.status_code == 201: # <5>
29+
response_json = response.json()
30+
print("Project created successfully:")
31+
print(f"Project ID: {response_json.get("@id", "Unknown ID")}")
32+
print(f"Project Name: {response_json.get('name', 'Unknown Name')}")
33+
else:
34+
print(f"Error creating project: {response.status_code} - {response.text}")
35+
36+
if __name__ == "__main__":
37+
host = init_sysmlv2_api()
38+
39+
# Fetch and display the list of projects currently available on the server
40+
print("Fetching the list of projects currently available on the server:")
41+
fetch_projects(host)
42+
43+
# Create a new project with a unique name by appending a timestamp
44+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
45+
project_name = f"New Project - {timestamp}"
46+
create_project(host, project_name)
47+
48+
# Fetch and display the updated list of projects after creating the new project
49+
print("Fetching the updated list of projects after creating a new project:")
50+
fetch_projects(host)
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# These examples are adapted from the SysML v2 API Cookbook, available at
2+
# https://github.com/Systems-Modeling/SysML-v2-API-Cookbook, maintained by the
3+
# Object Management Group (OMG).
4+
# The original cookbook is designed for use with Jupyter Lab.
5+
# These examples have been adapted to run as standalone Python scripts, making
6+
# them suitable for use in various environments, including SysON.
7+
# They showcase practical usage scenarios and may include additional functionality
8+
# or modifications tailored to specific needs.
9+
10+
import requests # <1>
11+
from init_api import parse_arguments
12+
from init_api import init_sysmlv2_api
13+
14+
def fetch_commits(host, project_id): # <2>
15+
commits_url = f"{host}/projects/{project_id}/commits" # <3>
16+
response = requests.get(commits_url) # <4>
17+
if response.status_code == 200: # <5>
18+
commits = response.json()
19+
for commit in commits:
20+
print(f"Commit ID: {commit['@id']}")
21+
return commits
22+
else:
23+
print(f"Error fetching commits: {response.status_code} - {response.text}")
24+
return None
25+
26+
# Retrieves the latest commit for a given project.
27+
def get_last_commit_id(host, project_id):
28+
commits = fetch_commits(host, project_id)
29+
if commits:
30+
last_commit = commits[-1] if commits else None
31+
if last_commit:
32+
last_commit_id = last_commit['@id']
33+
print(f"Last Commit ID: {last_commit_id}")
34+
return last_commit_id
35+
else:
36+
print("No commits available.")
37+
return None
38+
39+
if __name__ == "__main__":
40+
args = parse_arguments()
41+
host = init_sysmlv2_api()
42+
project_id = args.project_id
43+
fetch_commits(host, project_id)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# These examples are adapted from the SysML v2 API Cookbook, available at
2+
# https://github.com/Systems-Modeling/SysML-v2-API-Cookbook, maintained by the
3+
# Object Management Group (OMG).
4+
# The original cookbook is designed for use with Jupyter Lab.
5+
# These examples have been adapted to run as standalone Python scripts, making
6+
# them suitable for use in various environments, including SysON.
7+
# They showcase practical usage scenarios and may include additional functionality
8+
# or modifications tailored to specific needs.
9+
10+
import requests # <1>
11+
from init_api import parse_arguments
12+
from init_api import init_sysmlv2_api
13+
from fetch_commits import get_last_commit_id
14+
15+
def fetch_elements(host, project_id): # <2>
16+
commit_id = get_last_commit_id(host, project_id)
17+
# API endpoint to fetch elements of the commit
18+
element_get_url = f"{host}/projects/{project_id}/commits/{commit_id}/elements" # <3>
19+
# Send GET request to retrieve elements
20+
response = requests.get(element_get_url) # <4>
21+
if response.status_code == 200: # <5>
22+
elements = response.json()
23+
for element in elements:
24+
print(f"Element ID: {element['@id']}, Name: {element['name']}")
25+
return elements
26+
else:
27+
print(f"Error fetching elements: {response.status_code} - {response.text}")
28+
return None
29+
30+
if __name__ == "__main__":
31+
args = parse_arguments()
32+
host = init_sysmlv2_api()
33+
project_id = args.project_id
34+
fetch_elements(host, project_id)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# These examples are adapted from the SysML v2 API Cookbook, available at
2+
# https://github.com/Systems-Modeling/SysML-v2-API-Cookbook, maintained by the
3+
# Object Management Group (OMG).
4+
# The original cookbook is designed for use with Jupyter Lab.
5+
# These examples have been adapted to run as standalone Python scripts, making
6+
# them suitable for use in various environments, including SysON.
7+
# They showcase practical usage scenarios and may include additional functionality
8+
# or modifications tailored to specific needs.
9+
10+
import requests # <1>
11+
from init_api import init_sysmlv2_api
12+
13+
def fetch_projects(host): # <2>
14+
projects_url = f"{host}/projects" # <3>
15+
response = requests.get(projects_url) # <4>
16+
if response.status_code == 200: # <5>
17+
projects = response.json()
18+
for project in projects:
19+
print(f"Project Name: {project['name']}, ID: {project['@id']}")
20+
else:
21+
print(f"Error fetching projects: {response.status_code} - {response.text}")
22+
23+
if __name__ == "__main__":
24+
host = init_sysmlv2_api()
25+
# Get the projects
26+
fetch_projects(host)
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# These examples are adapted from the SysML v2 API Cookbook, available at
2+
# https://github.com/Systems-Modeling/SysML-v2-API-Cookbook, maintained by the
3+
# Object Management Group (OMG).
4+
# The original cookbook is designed for use with Jupyter Lab.
5+
# These examples have been adapted to run as standalone Python scripts, making
6+
# them suitable for use in various environments, including SysON.
7+
# They showcase practical usage scenarios and may include additional functionality
8+
# or modifications tailored to specific needs.
9+
10+
from init_api import parse_arguments
11+
from init_api import init_sysmlv2_api
12+
from fetch_commits import get_last_commit_id
13+
from get_owned_elements import get_element
14+
15+
def get_member_features(host, project_id, commit_id, element_id, member_type, indent):
16+
# Fetch the element
17+
element_data = get_element(host, project_id, commit_id, element_id, indent)
18+
if element_data:
19+
element_type = element_data ['@type']
20+
21+
if element_type == member_type:
22+
print(element_data)
23+
# Feature memberships
24+
element_features = element_data['ownedFeature']
25+
if len(element_features) > 0:
26+
for feature in element_features:
27+
get_member_features(host, project_id, commit_id, feature['@id'], member_type, indent + " ")
28+
29+
if __name__ == "__main__":
30+
args = parse_arguments()
31+
host = init_sysmlv2_api()
32+
project_id = args.project_id
33+
commit_id = get_last_commit_id(host, project_id)
34+
element_id = args.element_id
35+
36+
# Get Parts Tree
37+
print("Parts Tree:")
38+
get_member_features(host, project_id, commit_id, element_id, 'PartUsage', " ")
39+
40+
# Get Behaviour Tree
41+
print("Behaviours Tree:")
42+
get_member_features(host, project_id, commit_id, element_id, 'ActionUsage', " ")
43+
44+
# Get Requirements Tree
45+
print("Requirements Tree:")
46+
get_member_features(host, project_id, commit_id, element_id, 'RequirementUsage', " ")
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# These examples are adapted from the SysML v2 API Cookbook, available at
2+
# https://github.com/Systems-Modeling/SysML-v2-API-Cookbook, maintained by the
3+
# Object Management Group (OMG).
4+
# The original cookbook is designed for use with Jupyter Lab.
5+
# These examples have been adapted to run as standalone Python scripts, making
6+
# them suitable for use in various environments, including SysON.
7+
# They showcase practical usage scenarios and may include additional functionality
8+
# or modifications tailored to specific needs.
9+
10+
import requests
11+
from init_api import parse_arguments
12+
from init_api import init_sysmlv2_api
13+
from fetch_commits import get_last_commit_id
14+
15+
# Function to fetch an element and print its name and type
16+
def get_element(host, project_id, commit_id, element_id, indent):
17+
# Fetch the element in the given commit of the given project
18+
element_url = f"{host}/projects/{project_id}/commits/{commit_id}/elements/{element_id}" # <3>
19+
response = requests.get(element_url) # <1>
20+
21+
if response.status_code == 200:
22+
element_data = response.json()
23+
element_name_to_print = element_data['name'] if element_data['name'] else 'N/A'
24+
element_id = element_data ['@id']
25+
element_type = element_data ['@type']
26+
print(f"{indent} - {element_name_to_print} (id = {element_id} , type = {element_type})") # <2>
27+
return element_data
28+
else:
29+
return None
30+
31+
# Fetches immediate owned elements for a given element
32+
def get_owned_elements_immediate(host, project_id, commit_id, element_id, indent):
33+
element_data = get_element(host, project_id, commit_id, element_id, indent)
34+
if element_data:
35+
owned_elements = element_data['ownedElement']
36+
if len(owned_elements) > 0:
37+
for owned_element in owned_elements:
38+
get_element(host, project_id, commit_id, owned_element['@id'], indent + ' ')
39+
else:
40+
print(f"Unable to fetch element with id '{element_id}' in commit '{commit_id}' of project '{project_id}'")
41+
42+
# Fetches owned elements recursively for a given element
43+
def get_owned_elements(host, project_id, commit_id, element_id, indent):
44+
element_data = get_element(host, project_id, commit_id, element_id, indent)
45+
if element_data: # <3>
46+
owned_elements = element_data['ownedElement']
47+
if len(owned_elements) > 0:
48+
for owned_element in owned_elements:
49+
get_owned_elements(host, project_id, commit_id, owned_element['@id'], indent+' ')
50+
else:
51+
print(f"Unable to fetch element with id '{element_id}' in commit '{commit_id}' of project '{project_id}'") # <4>
52+
53+
if __name__ == "__main__":
54+
args = parse_arguments()
55+
host = init_sysmlv2_api()
56+
project_id = args.project_id
57+
commit_id = get_last_commit_id(host, project_id)
58+
element_id = args.element_id
59+
60+
#Get owned elements (immediate) for the given element in the given commit of the given project
61+
print("Immediate Owned Elements:")
62+
get_owned_elements_immediate(host, project_id, commit_id, element_id, '')
63+
64+
# Get owned elements (recursive) for the given element in the given commit of the given project
65+
print("\nRecursive Owned Elements:")
66+
get_owned_elements(host, project_id, commit_id, element_id, '')
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# These examples are adapted from the SysML v2 API Cookbook, available at
2+
# https://github.com/Systems-Modeling/SysML-v2-API-Cookbook, maintained by the
3+
# Object Management Group (OMG).
4+
# The original cookbook is designed for use with Jupyter Lab.
5+
# These examples have been adapted to run as standalone Python scripts, making
6+
# them suitable for use in various environments, including SysON.
7+
# They showcase practical usage scenarios and may include additional functionality
8+
# or modifications tailored to specific needs.
9+
import argparse
10+
11+
def init_sysmlv2_api():
12+
host = "http://localhost:8080/api/rest" # Replace with your actual API host URL # <1>
13+
return host
14+
15+
def parse_arguments():
16+
# Parse command-line arguments
17+
parser = argparse.ArgumentParser()
18+
parser.add_argument(
19+
"project_id",
20+
type=str,
21+
help="The project ID.",
22+
)
23+
parser.add_argument(
24+
"element_id",
25+
type=str,
26+
nargs="?", # This makes element_id optional
27+
help="The element ID (optional).",
28+
)
29+
return parser.parse_args()
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
= APIs cookbook
2+
The APIs cookbook offers a collection of practical examples and step-by-step instructions to help you interact with {product}’s REST APIs.
3+
It includes ready-to-use code snippets and explanations, allowing you to integrate with other tools, automate tasks, and explore advanced features efficiently.
4+
Each recipe aims for clarity, ease of use, and customizability for different use cases.
5+
6+
== Setup instructions
7+
To get started with the examples, Python is used to interact with {product}’s features and data.
8+
Python offers a powerful way to automate tasks, handle API calls, and process data, making it an ideal choice for this purpose.
9+
Follow the steps after to set up your environment and get everything ready to run the provided code snippets.
10+
11+
=== Step 1: Install required Python libraries
12+
Confirm you have the following Python libraries installed before running the code snippets:
13+
14+
* `requests`: For making HTTP requests to the {sysmlv2} API.
15+
* `pandas`: For organizing and manipulating data.
16+
17+
To install these libraries, run:
18+
19+
`pip install requests pandas`
20+
21+
=== Step 2: Configure {sysmlv2} API access
22+
23+
[source,python]
24+
.init_api.py
25+
----
26+
include::example$init_api.py[]
27+
----
28+
29+
TIP: Replace `http://localhost:8080` with the actual URL of your API server if hosted elsewhere.
30+
31+
*What this code does*:
32+
33+
<1> Define the base host: Assigns the variable `host` with the base URL of the {sysmlv2} API server.
34+
35+
[NOTE]
36+
====
37+
In the examples, the {product} server uses a randomization function to generate unique IDs, so outputs can differ when you run the examples on your project.
38+
====
39+
40+
Other code snippets use this function.
41+
To run it, see the following section about recipes.
42+
43+
=== Step 3: Test code snippets
44+
Once you have configured the {sysmlv2} API access, you can start testing the xref:developer-guide:api-cookbook.adoc#recipes[recipes].
45+
46+
=== Troubleshooting
47+
48+
. *Error Handling*:
49+
** Check endpoint URLs, `project_id`, `commit_id`, and `authentication` tokens if the API returns errors: for example, 400 or 500 status codes.
50+
** Confirm the API is running.
51+
. *Empty Responses*:
52+
** Verify that queried elements exist within the specified project and commit.
53+
** Use the {product} web interface for visual inspection.
54+
. *Recursive Function Depth*:
55+
** For large models, manage recursion depth appropriately.
56+
** Change the logic to handle large datasets by limiting recursion depth.
57+
58+
[#recipes]
59+
== Recipes
60+
61+
include::developer-guide:project_commit_branch_tag_recipe.adoc[leveloffset=+2]
62+
63+
include::developer-guide:element_owned_elements_recipe.adoc[leveloffset=+2]

0 commit comments

Comments
 (0)