Authenticating clients
You can use one of the Authorization endpoints of the CADMATIC Web API to create an access token for your client. To request the token, you need to provide the Client ID and the Secret Key of your client. After this, the other endpoints will work if you pass the access token in the header of your REST requests. If you are using the Web API via Swagger UI, you do not need to add the token to the header: the Swagger page does that for you.
Prerequisites
-
You have created a client for the Web API service.
-
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.
# Example how to authenticate to the Web API.
# This script will use the client ID and the client secret to authenticate to
# the Web API and receive an authentication token that can be used in
# subsequent requests. In this example, it is used to read the list of known
# project.
#
# Run this script with the following parameters:
# python webapi_authentication.py <Web API URL> <Client ID> <Client secret>
from requests import Session, post
from urllib.parse import urljoin
import sys
base_url, client_id, client_secret = sys.argv[1:4]
def create_session() -> Session:
"""Create an authenticated session to use with the Web API
"""
token_url= urljoin(base_url, "api/token")
reply = post(token_url, json={
"ClientID": client_id,
"ClientSecret": client_secret})
if reply.status_code != 200:
raise Exception("Authentication failure")
token = reply.json()["token"]
session = Session()
session.headers.update({'Authorization': 'Bearer '+token})
return session
with create_session() as session:
projects = session.get(urljoin(base_url, "api/servers/projects")).json()
print("Projects known to the Web API: ", projects)