Testing The Pantone API

Code Sandbox

The Code Sandbox project below can help you to test and run the Pantone API quickly just by opening the project on the following URL:
https://codesandbox.io/embed/pantone-api-example-cfwkcz?fontsize=14&hidenavigation=1&theme=dark

Python Implementation

Here is an example of implementing the Pantone API in Python using Boto3.

import json

import boto3
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.exceptions import ClientError

# %% ##########################################################################
"""
Setup: Define API production server information
"""
region = "us-east-1"
aws_service = 'appsync'
identity_pool_id = "us-east-1:0c09a4ec-8817-496f-b37d-3deef005f08b"
user_pool_id = "us-east-1_apCdkad4c"
client_id = "68fhh8dv6cmjdprd4uf37cp9r6"
api_endpoint = ("https://4n6dg5ccsfct3lzfssu34boemq.appsync-api"
                ".us-east-1.amazonaws.com/graphql")
auth_type = "AWS_IAM"

# Define your username and password
username = "YOUR_USERNAME"
password = "YOUR_PASSWORD"

# %% ##########################################################################
"""
Create function for signing the request using V4 Signature
"""


def signed_request(method, url, data=None, params=None, headers=None):
    request = AWSRequest(method=method, url=url, data=data,
                         params=params, headers=headers)

    SigV4Auth(creds, aws_service, region).add_auth(request)

    return requests.request(method=method, url=url,
                            headers=dict(request.headers), data=data)

# Create a Boto3 CognitoIdentityProvider client
client = boto3.client("cognito-idp", region_name=region)

# %% ##########################################################################
"""
Authenticate using the boto3 cognito-idp client and initiate auth to
retrive AWS Credentials
"""
try:
    response = client.initiate_auth(
        ClientId=client_id,
        AuthFlow="USER_PASSWORD_AUTH",
        AuthParameters={"USERNAME": username, "PASSWORD": password},
    )
    access_token = response["AuthenticationResult"]["AccessToken"]
    id_token = response["AuthenticationResult"]["IdToken"]
except ClientError as e:
    print(
        f"Unable to authenticate: {username}: {e.response['Error']['Message']}"
    )
    access_token = None

# %% ##########################################################################
"""
Register the Cognito Identity Client which will retrive Temporary
Credentials that we will need to use to sign the request
"""
# Initialize a Boto3 client for Cognito Identity
cognito_identity_client = boto3.client('cognito-identity', region_name=region)

identityId = cognito_identity_client.get_id(
    IdentityPoolId=identity_pool_id
)

# Get AWS credentials for the Cognito Identity ID
try:
    response = cognito_identity_client.get_credentials_for_identity(
        IdentityId=identityId['IdentityId'],
        Logins={
            f"cognito-idp.{region}.amazonaws.com/{user_pool_id}": id_token
        }
    )
except ClientError as e:
    print(
        f"Unable to retrieve AWS credentials: "
        f"{username}: {e.response['Error']['Message']}"
    )

# Extract the AWS credentials
aws_access_key_id = response['Credentials']['AccessKeyId']
aws_secret_access_key = response['Credentials']['SecretKey']
aws_session_token = response['Credentials']['SessionToken']

# %% ##########################################################################
"""
Create boto3 Session with temporary credentials
"""
session = boto3.Session(
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    aws_session_token=aws_session_token,
    region_name=region,
)

credentials = session.get_credentials()
creds = credentials.get_frozen_credentials()

# %% ##########################################################################
"""
This query will fetch all Pantone books from the API
"""
get_books = """
    query {getBooks {
            id
            title
            info {
            en {
                target
                description
                }
            }
        }
    }
"""

# Define the variable values as a dictionary
variables = {None: None}

try:
    response = signed_request(
        "POST",
        url=api_endpoint,
        data=json.dumps({"query": get_books, "variables": variables}),
        headers={"Content-Type": "application/json"},
    )
    print(response.text)
except ClientError as e:
    print(e)

# %% ##########################################################################
"""
This query will return all colors for specific book
"""
get_book = """
    query ($bookId: ID!) {
        getBook(id: $bookId) {
            id
                colors {
                code
                name
                rgb {r g b}
                colorValues {
                    M0 {spectral {values}
                    }
                }
                positionInBook
                }
        }
    }
"""

# Define the variable values as a dictionary
variables = {"bookId": "pantoneSolidCoated"}

try:
    response = signed_request(
        "POST",
        url=api_endpoint,
        data=json.dumps({"query": get_book, "variables": variables}),
        headers={"Content-Type": "application/json"},
    )
    print(response.text)
except ClientError as e:
    print(e)

# %% ##########################################################################
"""
This query will get the available color data for a specific color code.
"""

colors_by_code = """
    query ($codes: [String]) {
        getColorsByCode(codes: $codes) {
                code
                lab { l a b }
                cmyk {c m y k}
                rgb {r g b}
                pageNumberInBook
                colorValues {
                    M0 {spectral {values}
                }
                    M1 {spectral {values}
                }
                    M2 {spectral {values}
                }
                    M3 {spectral {values}
                }
                    SpInUVInc {spectral {values}
                }
                    SpInUVCal {spectral {values}
                }
                    SpInUVExc {spectral {values}
                }
                    SpExUVInc {spectral {values}
                }
                    SpExUVCal {spectral {values}
                }
                    SpExUVExc {spectral {values}
                }
            }
        }
    }
"""

# Define the variable values as a dictionary
variables = {"codes": ["3570 C", "3570 U"]}

try:
    response = signed_request(
        "POST",
        url=api_endpoint,
        data=json.dumps({"query": colors_by_code, "variables": variables}),
        headers={"Content-Type": "application/json"},
    )
    print(response.text)
except ClientError as e:
    print(e)