Cadmatic Web API Userguide
Cadmatic Web API Userguide
All rights reserved. No part of this publication may be reproduced or transmitted in any form or by
any means without the express written permission of the publisher.
CADMATIC is a registered trademark of Cadmatic Oy. All other marks are property of their
respective owners.
Cadmatic
Linnankatu 52
20100 Turku
Finland
Tel. +358 2 412 4500
www.cadmatic.com
The Web API works independently of the Cadmatic design applications: it only interacts with the
Common Object Storage (COS) databases that have been added to its configuration. You can install
the Web API to any site that has a COS installation; you can connect multiple COS servers from
different projects and external databases to the same Web API.
The Web API is run as a Windows service, and there can be several service instances and application
versions running simultaneously. Starting the service attempts to open a session to the COS servers
that have been configured for that service instance, and after the service has established the
connection, other systems can start accessing the data via the API. The service runs an embedded
web server that receives incoming requests and returns the requested information to the
requesting party. The API does not store the state between separate requests, which simplifies
communication across different integration solutions as all communication can happen in parallel.
l COS objects
o Read the attributes and properties of any COS objects using their OID.
o Read references to COS objects.
l Document publication files
o When the design documents are ready, you can fetch the final documents to the
project's repository using CADMATIC Web API.
l Objects with a position ID and attributes
o You can create, for example, equipment, valves, instruments and their attribute data
from an ERP or PLM before starting the actual design work in Cadmatic applications.
The designer can then use the ready-made objects in the 3D model or P&I diagram.
o Users can also link the object from, for example, PLM or ERP to the instance of the
object in Cadmatic applications.
o List piping, cable tray, and ducting specifications, along with the parts belonging to
each specification.
l Status
o Get the status of connectors.
l Systems and pipelines
o List all systems and pipelines
In a multi-site scenario, the Web API can be installed to an online replica site. Some of the
endpoints request the ownership of objects directly from COS.
Prerequisites
l You have administrator privileges on the target computer.
Do the following:
1. Open the CADMATIC Web API Installer dialog.
2. Click Install New. The Install New Service dialog opens.
Tip: The configuration folder has the ".stc" suffix in its name (<workstationname>.stc),
and it contains the workstation profiles in the wsprofile subfolder.
l Workstation profile – Select the workstation profile that the service is to use.
l Data Directory – The service stores its data in
%ProgramData%\CADMATIC\WebApi\<service name> by default; click Browse if you
want to change this location.
Important: The data folder must be empty and located on a local drive: you cannot use
a network drive for this. The service account must have modify rights to
the selected folder, or the service installation will fail.
l Service account – Select the account type that the service is to use.
o Local System – Select this to run the service as a Local System account that has
extensive privileges on the local computer and in the network. This account type
should not normally be used in a production environment, but it could be useful
in a test environment. This account type acts as a computer on the network, and
it does not have a password.
o Local Service – Select this to run the service as a Local Service account that is
specifically intended for services for security. This account type has minimum
privileges on the local computer, so your computer is still relatively safe even if
the service is compromised. The account cannot access most of the folders on
the local computer by default, so you must explicitly give this account full control
to each project folder that you want the service to be able to use. The account
presents anonymous credentials on the network.
o Network Service – Select this to run the service as a Network Service account.
This is similar to a Local Service account in that it has minimum privileges on the
local computer, so your computer is still relatively safe even if the service is
compromised, and you must explicitly give it full control to the project folders.
The differences are that this account type has the permissions for 'Log on as a
service' and 'Impersonate a client after authentication' by default, and it
identifies itself in the network by using the credentials of the computer account.
o Other Account – Select this to run the service as a specific user account that
requires a username and a password. Enter the required credentials in the
Account (DOMAIN\user) and Password fields.
Tip: In production environments, the account type is usually set to either Local Service
or Network Service. For more information on service accounts, see
https://docs.microsoft.com/en-us/windows/win32/services/service-user-
accounts.
l Start on system startup – Select this option if you want the service to be running
whenever the computer is on. You can always start and stop the service as needed,
using either the Web API management tools or Windows services.
4. Click Install. You are prompted if the installing succeeded.
5. You can now configure the service as described in Configuring a service and then start it as
described in Starting a service.
Do the following:
1. Open the CADMATIC Web API Installer dialog.
2. Select the service to be upgraded, and click Upgrade.
3. In the Upgrade Service dialog, review the following settings.
l Configuration directory – Make sure the correct configuration folder is selected.
l Workstation profile – Make sure the correct workstation profile is selected.
4. Click OK. You are prompted if the upgrade succeeded.
Do the following:
Prerequisites
l The SSL certificate has been installed.
l The COS server and the user settings have been defined, as described in Configuring a service.
Do the following:
1. Open the CADMATIC Web API Management Tools dialog.
2. Select the required Web API service from the drop-down list, and click Start.
When a Web API service is running, you can select the service from the drop-down list and click
Stop to stop the service. You must do this, for example, if you want to clear the list of calls to
deprecated and sunset endpoints, as described in Viewing statistics.
Do the following:
b. To add a project, click Add Project and browse to the <projectdbname>.pms folder that
contains the project database . The COS address field shows the address of the COS
server, and you can add more projects that use the same COS server.
c. To define how to authenticate the service in COS, do the following:
l If the service was installed as Local System, Local Service or Network Service,
enter the COS username and password to use.
l If the service was installed as Other Account, you can select the Use Windows
credentials option to use the same Windows account that the service is using
also for accessing COS. This requires that the Windows user account is a valid
COS user account. Otherwise, clear the option and specify the COS username and
the COS password to use.
5. Click Save.
6. You can now start the service, as described in Starting a service.
Important: This procedure provides you with the Name, the Client ID, and the Secret Key of the
new client. You will need this information when creating an access token for the client.
Do the following:
1. Open the CADMATIC Web API Management Tools dialog.
2. Select the required Web API service from the drop-down list, and click Clients.
3. In the Clients dialog, click Add Client.
4. In the Client Name dialog, enter a name (5–256 characters, spaces are allowed) for the client,
and click OK.
5. In the Secret Key dialog, click Copy to copy the Secret Key to the clipboard.
Important: Store the key in a safe place. Once you close this dialog, there is no way to
recover the key.
6. In the Clients dialog, you can see the Name and the Client ID of the new client. You can now
create an access token for the new client, for example, as described in Creating access
tokens.
Do the following:
update your code to use these newer endpoints. The formal process of first deprecating, then
sunsetting, and finally removing endpoints is described in Endpoint deprecation process.
Prerequisites
l If you intend to reset the statistics, you must stop the Web API service.
Do the following:
3. If the dialog lists any calls to deprecated or sunset endpoints, make a note of those calls so
that you can start planning when to stop using them.
4. You can clear the list by clicking Reset statistics. If the service is running, you are prompted
that it must be stopped first.
5. Click Close.
You can open the reference page in a web browser from this link:
https://docs.cadmatic.com/webapi/2024T3/Content/Topics/WebAPI_reference.html
4.1.2. Swagger UI
Swagger is an open-source toolkit that helps developers design, build, and document REST APIs. A
Swagger page, or Swagger UI, provides a user-friendly interface to the API, enabling developers to
understand its capabilities, interact with its endpoints, and test it directly from the web browser
without needing to write code. Thus, it serves as both an interactive API documentation and a
testing tool.
You can open the Swagger UI page in a web browser by entering the URL that was used to configure
the Web API service.
On the Swagger page, you can browse the available endpoints. For each endpoint, it shows the
applicable HTTP method, a description, a list of parameters, responses and examples. The required
parameters are indicated in the Web API reference page.
If you have the information that is required for authenticating your client, you can also test the
endpoints on the Swagger page.
Do the following:
1. Enter the URL of the Web API in a web browser. The Swagger page opens.
2. Click . The Available authorizations view opens.
3. Enter the authentication information, and click the button of the given
authorization method.
l To use JSON authorization, enter the value as Bearer x where x is the token.
l To use OAuth 2.0 Client Credentials, enter the Client ID and the Secret Key.
Once authorization is granted, you can try out the endpoint functions on the Swagger page.
If the database name is unique in the given environment, the identifier string only needs to specify
the name.
l Specify the name of the target database in the format dbName.dbExtension.
In this example, there is only one database with the name webapi_dev.pms, so that works as
the identifier:
In this example, the response indicates that ProjectA.pms is not a unique database name:
If the database name is not unique in the given environment, you must also identify the server. This
can happen especially in replicated projects where both the master server and replica servers are
connected to the Web API, and replicated databases have inherited their name from the master
database.
l Specify the name and the location of target database in the format
dbName.dbExtension@serverID where serverID is one of the following: server name (might
not be unique), server address (guaranteed to be unique), or server COS OID (practically
guaranteed to be unique).
In this example, the database is identified by its name and the COS OID of the server:
Endpoints that require the target to be a project database do not implicitly query the library
database.
The following example shows a request that primarily reads all objects from a project database
(webapi_dev.pms), but the response also includes objects from the library database (webapi_
dev.lib) that the project is using. (Image taken from the Swagger UI page, with access token
missing.)
The same mechanism is also applied to operations that target individual objects: you can read,
modify, and delete objects with implicit library queries. If the targeted object is located in /
{library}/objecttype/oid, you can access it also via /{project-using-the-library}/objecttype/oid.
However, creating a new object always creates it in the specified database. If you create a new
object under /{library}/objecttype, then it is created in the library database. If you create a new
object under /{project-using-the-library}/objecttype, then it is created in the project database.
The CADMATIC Web API supports the following filtering methods: query filters, reply filters, and
pagination. Query filters and reply filters are supported on all GET endpoints that return a collection
of items, while pagination is only supported on selected GET endpoints.
You can include multiple query filters or use both query filters and reply filters in the same call. If
the call includes multiple query filters, the results from the individual queries are combined using a
logical AND operator. Combining multiple query filters with OR is not directly supported, but you
can perform multiple GET requests and combine the results on the client side.
where
l <neg> is an optional exclamation mark (!) that causes each condition to be negated and
evaluated separately. Negation is most useful when the filter does not include an optional
operator–value condition.
l <jsonfield>|<jsondictfield>|attributes(<string>) specifies the targeted field
in the response. The query checks whether the field exists and evaluates for false if it does
not.
o <jsonfield> specifies the targeted JSON property using dot
notation: object.properties.objectType="Drawing"
o <jsondictfield> specifies the targeted JSON property using bracket notation:
[<string>]. You can also mix dictionary like access and the <jsonfield> path:
["object"].properties["objectType"]="Drawing"
o attributes(<string>) specifies a COS attribute tag as "<string>". If the string
itself contains double-quote (") or backslash (\) characters, they must be escaped with
the backslash (\) character.
l <operator><value> defines an optional condition of the targeted field. If the operator is
specified, then also the value must be given.
o <operator> can be one of the following:
= equal to
!= not equal to
R regular expression
Note: The use of comparison operator requires the value to be a string, a number, or a
Boolean. Other types of values cause the filter to be ignored.
o <value> can be one of the following, depending on the data type of the JSON field:
list A comma-separated list of items inside square brackets, where each item
is a quoted string or a number:
[<item1>, <item2>, …, <itemn>]
If the filter has an operator–value condition, it checks if the field exists and if its value satisfies the
given condition.
l ?query=properties.ModificationTime>1645034215
The filter finds objects where 'ModificationTime' is greater than the given value.
If the filter is negated with a leading exclamation mark, it evaluates each part of the filter expression
separately.
l ?query=!properties.ModificationTime
The filter finds objects that do not have the 'ModificationTime' property.
l ?query=!properties.ModificationTime>1645034215
The filter finds (a) objects that do not have the 'ModificationTime' property and (b) objects
where 'ModificationTime' is not greater than the given value.
If the filter contains an element that is an array, the rest of the filter's path is used to evaluate every
item in the array. If at least one of the items matches the filter, the object is considered a match.
l ?query=connectionPoints.data.tg1
The filter finds objects where any of the connection points has the key 'tg1' in its data.
l ?query=!connectionPoints.data.tg1
The filter finds objects where none of the connection points has the key 'tg1' in its data.
l ?query=!connectionPoints["data"]["a.b"]
The filter uses bracket notation to find objects where none of the connection points has the
key 'a.b' in its data. The filter cannot use dot notation because the key contains a dot, which is
a special character.
If the filter tries to compare the value of an element that is an array, the filter is ignored.
l ?query=connectionPoints=5
The filter is ignored. An array cannot equal a number or a string.
You can include multiple reply filters or use both reply filters and query filters in the same call.
l <exclusionSpecifier> can be either '-' or '+', and it can target all the fields or just a
specific field.
o -<fieldName> removes the specified field from the response.
o - removes all the fields from the response. If none are put back, the object remains as
an empty object.
o +<fieldName> (or just <fieldName>) adds the specified field back into the response.
o + adds all the fields back into the response.
l <jsonfield> specifies the targeted JSON field using dot notation.
Because attributes are not hard-coded special fields, but rather runtime values, they cannot
be specified by the <jsonfield> syntax.
l attributes(<string>) specifies attributes in the targeted field. <string> is a double-
quoted string that contains the tag name of some COS attribute. If the string itself contains
double-quote (") characters, they must be escaped with the backslash (\) character.
If the call includes more than one reply filter, the filters are applied in the order that they are given.
l ?reply=-,foobar
If an object in the response has these properties:
{
"foo" : "bar"
"bar" : 123
"foobar": [1, 2, 3]
}
the first filter removes every property from the object and the second filter puts the 'foobar'
property back into it:
{
"foobar": [1, 2, 3]
}
If the path of the reply filter includes a field that is an array, the filter is applied to all the items in
the array.
l ?reply=-foobar.a
If an object in the response has this property:
{
"foobar": [{ "a": 1 }, {"b": 2}, {"a": 1}]
}
the filter removes all the 'a' fields from the property:
{
"foobar": [{}, {"b": 2}, {}]
}
4.3.3. Pagination
You can add pagination to the query string to start reading the response from a specific object
(numeric offset, key-based offset), and to read only a subset of the objects from the response
(limiting).
Numeric offset
In numeric offset, the 'offset' parameter specifies the zero-based index of the first object to be read
(that is, how many objects to skip before starting to read).
GET api/Project.pms/catalogParts?offset=10
Key-based offset
In key-based offset, the 'after' parameter specifies the COS OID of the object after which to start the
reading.
GET api/Project.pms/catalogParts?after=GkbG.pzZHiACC6j4RQYmE0
Limiting
In limiting, the 'limit' parameter defines the maximum number of objects to be read from the set.
GET api/Project.pms/catalogParts?limit=50
GET api/Project.pms/catalogParts/?limit=50
GET api/Project.pms/catalogParts/?after=GkbG.pzZHiACC6j4RQYmE0&limit=50
Page consistency
Reading the same page again keeps the same order of items, but the list of items might change.
l If an object has been removed from COS, re-reading the page removes the object from the
page.
l If a new object has been added into COS, re-reading the page adds the object to the page, in
accordance with the existing order of items.
Therefore, clients must not assume that re-reading a page will always return exactly the same
results.
Task: Get all catalog parts that have the 'Author' attribute (tag 'U00' in our examples) from the
project database ('Project.pms' in our examples).
Query string:
?query=attributes("U00")
Example query:
GET api/Project.pms/catalogParts/?query=attributes("U00")
Task: Get all catalog parts that have the 'Author' attribute set to 'Cadmatic User' from the project
database.
Query string:
?query=attributes("U00")="Cadmatic User"
Example query:
Task: Get all catalog parts that do not have the 'Author' attribute from the project database.
Query string:
?query=!attributes("U00")
Example query:
GET api/Project.pms/catalogParts/?query=!attributes("U00")
Task: Get all changes that have been made to model objects in the project database.
Query string:
?query=objectType="ModelObject"&query=transactionType="Modified"
Example query:
GET
api/Project.pms/changes/?query=objectType="ModelObject"&query=transactionType="Modif
ied"
Task: Get all catalog parts from the project database. Save bandwidth by excluding all of their
properties and references to model objects from the response.
Query string:
?reply=-properties,-referencedObjects
Example query:
GET api/Project.pms/catalogParts/?reply=-properties,-referencedObjects
Task: Include the creation time of the object, but exclude all other properties from the response.
Query string:
?reply=-properties,properties.creationTime
Task: Get all catalog parts created by a specific author within the last two days. Times must be given
as a Unix timestamp; for the purposes of this example, we assume that timestamp '1673524566'
represents some time from two days ago. Exclude all properties, including the 'Author' attribute,
from the response (the author is the same for every part).
?reply=-properties,-attributes("U00")
Then, let's create query filter strings for specific values of 'Author' and 'CreationTime':
?query=attributes(“U00”)="Cadmatic User"
?query=properties.CreationTime>=1673524566
Finally, let's combine the reply filter and the query filters into one query string:
?reply=-properties,-attributes("U00")&query=attributes("U00")="Cadmatic
User"?query=properties.CreationTime>=1673524566
So, this query returns all catalog parts that were created in the last two days and where 'Author' is
set to 'Cadmatic User'. The response itself will not include the 'Author' attribute or any of the
properties since the Web API was explicitly told to remove them from the response.
Task: Get the objects whose COS object type is or is not 'Model Object' or 'Catalog Part'.
Query strings:
Task: Get the Systems where the 'Name' attribute (tag '.dD') contains the substring 'water' or
'Water'.
Query string:
?query=Attributes(".dD")=R"water|Water"
Task: Get the entities whose creation time is at least a given point in time.
4.4.1. Deprecation
An endpoint that is deprecated is no longer receiving any updates, but still remains fully functional
in the API.
HTTP header
Using a deprecated endpoint returns the following HTTP header in the response:
Deprecation: true
In addition, the "Link" header of the HTTP response has a link to this documentation page:
Link: <http://docs.cadmatic.org>; rel="deprecation", type=text/html
Note: The link header might also contain entries that are not related to the deprecation status.
4.4.2. Sunsetting
An endpoint that is sunset has a definite date after which the endpoint will be removed from the
API. Until then, the endpoint is no longer receiving any updates, but still remains fully functional in
the API.
For the users, the sunset date is not a fixed deadline: the endpoint keeps working until the user
organization upgrades the Web API to a version that has been released after the sunset date.
HTTP header
Using a sunset endpoint returns the following kind of HTTP header in the response, in accordance
with RFC 8594:
Sunset: HTTP-date
HTTP-date is defined in section-7.1.1.1 of RFC 7231. A real-world example of the response would
look like this:
Sunset: Sat, 31 Dec 2025 23:59:59 GMT
In addition, the "Link" header of the HTTP response has a link to this documentation page:
Link: <http://docs.cadmatic.org>; rel="sunset", type=text/html
Note: The link header might also contain entries that are not related to the sunsetting status.
4.4.3. Removal
An endpoint that has been removed provides an error response if used.
Related Topics
In actual integration, building access tokens must be part of the integration software. For testing
purposes, you can build them with any suitable software, such as Windows PowerShell or Insomnia.
Prerequisites
l Name, Client ID, and Secret Key of the client. These are defined when creating a new client,
as described in Adding clients.
Code example
The following Windows PowerShell code returns an access token. In the fields URL, Name,
ClientID, and ClientSecret, replace the values with values from your project.
1 $Url = "http://localhost:25001/api/token"
2 $Body = @{
3 Name = "Client_1"
4 ClientID = "4A21D8D846BF98541184BEB96802BD9D"
5 ClientSecret = "irjdgoE9Dqa4KdAladbO5zSB7JOo8IHQWO8NwAhqxz8="
6 } | ConvertTo-Json
7
8 Invoke-RestMethod -Method 'Post' -Uri $Url -Body $Body -ContentType "application/json"
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzY2NjgxNDN9.XyxYgHqj
n8Q2Moz2B3dANixII-7LpDbabhpTywHEDow
Prerequisites
l You have created a client for the Web API service.
l You know the Client ID and the Secret Key of your client.
Code example
The following Python code uses an access token to create an authenticated session, and then reads
the list of available projects from the Web API.
Code example
The following Python code demonstrates how to connect to the Web API, get the list of all available
projects, and wait until all the projects are ready to be used. Real client code would only need to
wait for those projects that the client wants to use.
Prerequisites
l To run the example script, you need the OID of the target document. You can get it with api/
{projectName}/documents.
l The script assumes that the target document has a publication with revision 'A'.
Code example
The following Windows PowerShell code gets the list of files from the publication and then
downloads the files.
1 $ProjectDatabase = "ExampleProject.pms"
2 $DocumentName = "ExampleDrawing"
3 $DrawingRevision = "A"
4 $DrawingOid = "Ftoxvd5LGskntwQCM7bugW"
5
6 $token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODIxODM5MDV9.hDYjnQzoEi9xq2AXI1-
lYJ5WtfQ6DWIwunkx0IoxSRU"
7
8 # Endpoint for listing files in a publication
9 $ListFilesUrl =
"http://localhost:25000/api/$ProjectDatabase/documents/$DrawingOid/$DrawingRevision/files/"
10
11 $Headers = @{"Authorization" = "Bearer " + $token}
12
13 $filesList = Invoke-RestMethod -Method Get -Uri $ListFilesUrl -Headers $Headers -ContentType
"application/json"
14
15 # Download each file with the file download endpoint
16 for (($i = 0); $i -le ($filesList.Length - 1); $i++)
17 {
18 $filename = $filesList[$i]
19 $fileDownloadUrl =
"http://localhost:25000/api/$ProjectDatabase/documents/$DrawingOid/$DrawingRevision/files/$filenam
e"
20 $savePath = "C:\tmp\" + $filename # Local place where we are saving the files
21
22 Invoke-WebRequest -Method Get -Uri $fileDownloadUrl -Headers $Headers -OutFile $savePath
23 }
Prerequisites
l The attributes have been assigned to the "External Data Management" object type in COS.
Otherwise, the system will display an error.
Code example
The following Windows PowerShell code creates a new EDM object and assigns the attribute
"Description-Dsc" to it.
1 ProjectDatabase = "ExampleProject.pms"
2 $token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODIxODYzNzJ9.DK9AxPlogjdmSEcTz-
PsK2Iu7Tr97MM5SgCdCwgs4WE"
3 $Headers = @{"Authorization" = "Bearer " + $token}
4
5 # Define the EDM
6 $EDMs = @(
7 @{
8 positionId = "examplePositionID"
9 externalId = "ID_2" # Must be unique among all EDM objects
10 system = "rC8izVTyIbc9onnRefpwtG" # OID for a CADMATIC system
11 line = "tyuEYX3qHl2ib096ieP.TG" # OID for a CADMATIC pipeline
12
13 # Add one attribute, description. Must first be assigned to the EDM type
14 attributes = @(
15 @{
16 tag = "Dsc"
17 value = "Example EDM Object from Web API"
18 }
19 )
20 }
21 )
22
23 # Convert the EDM to a JSON list, we need to specify depth = 3 since the attributes are nested
inside the EDM object
24 $JSON_EDM_list = ConvertTo-Json -Depth 3 -InputObject $EDMs
25
26 # Create the EDM
27 $EDM_create_url = "http://localhost:25000/api/$ProjectDatabase/edm/create"
28
29 $result = Invoke-RestMethod -Method Post -Uri $EDM_create_url -Headers $Headers -Body $JSON_EDM_
list -ContentType "application/json"
30
31 # Display the OID and external ID of the created object, they are returned as result
32 echo $result.oid
33 echo $result.externalId
Note: If a Plant Modeller service is just checking out the EDM object for an update, for example
because a user is inserting the object to the model at the same time, there may be a
temporary error of not being able to update the EDM object.
Prerequisites
l To be able to update an EDM object, you need to know its OID. You get the OID when you
create the EDM object.
Code example
The following Windows PowerShell code updates the value of the attribute "Description-Dsc" in an
existing EDM object.
1 $ProjectDatabase = "ExampleProject.pms"
2 $token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODIxODYzNzJ9.DK9AxPlogjdmSEcTz-
PsK2Iu7Tr97MM5SgCdCwgs4WE"
3 $Headers = @{"Authorization" = "Bearer " + $token}
4
5 # Here we define the EDM we are updating, note that you must specify the OID
6 $EDMs = @(
7 @{
8 oid = "vovsaRG1GrwXxgToFQLRF0"
9 positionId = "updated position ID"
10 externalId = "ID_2" # Must be unique among all EDM objects
11 system = "rC8izVTyIbc9onnRefpwtG" # OID for a CADMATIC system
12 line = "tyuEYX3qHl2ib096ieP.TG" # OID for a CADMATIC pipeline
13
14 # Add one attribute, description. Must first be assigned to the EDM type
15 attributes = @(
16 @{
17 tag = "Dsc"
18 value = "Updated description"
19 }
20 )
21 }
22 )
23
24 # Convert the EDM to a JSON list, we need to specify depth = 3 since the attributes are nested
inside the EDM object
25 $JSON_EDM_list = ConvertTo-Json -Depth 3 -InputObject $EDMs
26
27 # Now we can create the EDM
28 $EDM_update_url = "http://localhost:25000/api/$ProjectDatabase/edm/update"
29
30 $result = Invoke-RestMethod -Method Post -Uri $EDM_update_url -Headers $Headers -Body $JSON_EDM_
list -ContentType "application/json"
Code example
The following Windows PowerShell code uses the endpoint that returns all attributes for all
matching model objects. If you want to filter some of the attributes, use the function
webapiModelQueryOid.
1 $ProjectDatabase = "ExampleProject.pms"
2 $token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODIxODYzNzJ9.DK9AxPlogjdmSEcTz-
PsK2Iu7Tr97MM5SgCdCwgs4WE"
3 $Headers = @{"Authorization" = "Bearer " + $token}
4
5 # OID of the model query is needed
6 $modelQueryOid = "qNGTv1DqGZo4jxgs2Kl0hW"
7
8 $modelQueryUrl = "http://localhost:25000/api/$ProjectDatabase/pm/model/query/all/$modelQueryOid"
9
10 # Result is a list of matching model objects. The OID of each object as well as their attributes
are returned.
11 $modelObjects = Invoke-RestMethod -Method Get -Uri $modelQueryUrl -Headers $Headers -ContentType
"application/json"
12
13 # Display the result in command prompt
14 echo $modelObjects
There is a Plant Modeller script for mass-creating Web API queries by selecting Systems with a user
interface: %PMS_HOME%\pm\macro\CreateWebApiQueriesBySystem.mac
Code example
The following Python code shows how to detect if a given endpoint is either deprecated or sunset
by checking whether the HTTP header of the response includes either "Deprecation" or "Sunset".
The same approach can be used with any endpoint in the Web API, to automate a pre-processing
step.
6
7 def create_session() -> Session:
8
9 """Create an authenticated session to use with the Web API
10 """
11 token_url = base_url+"/api/token"
12 reply = post(token_url, json={
13 "ClientID": client_id,
14 "ClientSecret": client_secret})
15 if reply.status_code != 200:
16 raise Exception("Authentication failure")
17 token = reply.json()["token"]
18 session = Session()
19 session.headers.update({'Authorization': 'Bearer '+token})
20 return session
21
22 with create_session() as session:
23 # Use the first configured project database
24 projects = session.get(base_url+"/api/servers/projects").json()
25 project_database = projects[0]["project"]
26
27 parts = session.get(base_url+f"/api/{project_database}/parts/")
28 if "Deprecation" in parts.headers.keys():
29 print("Deprecated endpoint used")
30 if "Sunset" in parts.headers.keys():
31 print("Sunset endpoint used")