Skip to content

Instantly share code, notes, and snippets.

@mofosyne
Created September 16, 2024 15:42
Show Gist options
  • Save mofosyne/e15bb122024ff97ecc707dac68ab92b5 to your computer and use it in GitHub Desktop.
Save mofosyne/e15bb122024ff97ecc707dac68ab92b5 to your computer and use it in GitHub Desktop.
Digikey Basic Product Search Script (Targeting Digikey API v4)
#!/usr/bin/env python3
# digikey_api_v4_product_search.py
# Digikey Basic Product Search Script (Targeting Digikey API v4)
# By Brian Khuu 2024
# This is a digikey api v4 script that is focused only on just the flow needed to get product information.
# Recommend Reading:
# - https://developer.digikey.com/documentation
# - Section "OAuth 20: 2 Legged Flow" has good information on basic authnetic
# Design Principle: This script is written to be self contained besides requests and for each callout function to be composable
# This lacks much of more advance oauth implementation like token caching.
# Also this is restricted to sandboxed api at the moment...
# However this is okay as this was done as a learning exercise in addition to being for one-off internal projects.
# Other Similar Code:
# - https://github.com/alvarop/dkbc/blob/master/dkbc/dkbc.py
# - Just found this while coding this up which was very helpful in figuring out what I was missing
import os
import json
import requests
DIGIKEY_CLIENT_ID=os.getenv("DIGIKEY_CLIENT_ID")
DIGIKEY_CLIENT_SECRET=os.getenv("DIGIKEY_CLIENT_SECRET")
DIGIKEY_AUTH_URL_V4 = 'https://sandbox-api.digikey.com/v1/oauth2/authorize'
DIGIKEY_TOKEN_URL_V4 = 'https://sandbox-api.digikey.com/v1/oauth2/token'
DIGIKEY_PRODUCT_SEARCH_URL_V4 = 'https://sandbox-api.digikey.com/products/v4/search/keyword'
# Sanity Check That Authorisation Details Was Provided
if not DIGIKEY_CLIENT_ID or not DIGIKEY_CLIENT_SECRET:
print("Missing client id or secret")
quit()
def oauthV2_get_simple_access_token(url, client_id, client_secret):
# Get the simple access token required for 2 Legged Authorization OAutV2.0 flow
# This is typically used for basic search and retreival of publically avaliable information
response = requests.post(
url,
data={
"client_id": client_id,
"client_secret": client_secret,
"grant_type": "client_credentials",
}
)
return response.json()
def oauthv2_product_search(url, client_id, token, keyword):
# Dev Note: Why did I not just place the data?
# https://stackoverflow.com/questions/15737434/python-requests-module-urlencoding-json-data
data_payload = {
"Keywords": str(keyword),
}
response = requests.post(
url,
headers = {
"X-DIGIKEY-Client-Id": client_id,
"authorization": "Bearer {access_token}".format(access_token=token.get("access_token")),
"content-type": "application/json",
"accept": "application/json",
},
data = json.dumps(data_payload)
)
return response.json()
oauth_token = oauthV2_get_simple_access_token(DIGIKEY_TOKEN_URL_V4, DIGIKEY_CLIENT_ID, DIGIKEY_CLIENT_SECRET)
print(oauth_token)
search_result = oauthv2_product_search(DIGIKEY_PRODUCT_SEARCH_URL_V4, DIGIKEY_CLIENT_ID, oauth_token, "MCP2221A-I/SL-ND")
print(json.dumps(search_result, indent=4))
@mofosyne
Copy link
Author

This is the expected output of this script

{'access_token': '<<REDACTED>>', 'expires_in': 599, 'token_type': 'Bearer'}
{
    "Products": [
        {
            "Description": {
                "ProductDescription": "CAP ALUM 1000UF 20% 35V RADIAL",
                "DetailedDescription": "Aluminum Electrolytic Capacitors Radial, Can 2000 Hrs @ 105\u00b0C"
            },
            "Manufacturer": {
                "Id": 10,
                "Name": "Panasonic Electronic Components"
            },
            "ManufacturerProductNumber": "ECA-1VHG102",
            "UnitPrice": 1.03,
            "ProductUrl": null,
            "DatasheetUrl": null,
            "PhotoUrl": null,
            "ProductVariations": [
                {
                    "DigiKeyProductNumber": "P5555-ND",
                    "PackageType": {
                        "Id": 3,
                        "Name": "Bulk"
                    },
                    "StandardPricing": [
                        {
                            "BreakQuantity": 1,
                            "UnitPrice": 1.03,
                            "TotalPrice": 1.03
                        },
                        {
                            "BreakQuantity": 10,
                            "UnitPrice": 0.79,
                            "TotalPrice": 7.9
                        },
                        {
                            "BreakQuantity": 100,
                            "UnitPrice": 0.56,
                            "TotalPrice": 56.0
                        },
                        {
                            "BreakQuantity": 500,
                            "UnitPrice": 0.44,
                            "TotalPrice": 220.0
                        },
                        {
                            "BreakQuantity": 1000,
                            "UnitPrice": 0.38,
                            "TotalPrice": 380.0
                        },
                        {
                            "BreakQuantity": 2500,
                            "UnitPrice": 0.35,
                            "TotalPrice": 875.0
                        },
                        {
                            "BreakQuantity": 5000,
                            "UnitPrice": 0.33,
                            "TotalPrice": 1650.0
                        }
                    ],
                    "MyPricing": [
                        {
                            "BreakQuantity": 1,
                            "UnitPrice": 0.74,
                            "TotalPrice": 0.74
                        },
                        {
                            "BreakQuantity": 10,
                            "UnitPrice": 0.43,
                            "TotalPrice": 4.3
                        },
                        {
                            "BreakQuantity": 5000,
                            "UnitPrice": 0.33,
                            "TotalPrice": 1650.0
                        }
                    ],
                    "MarketPlace": false,
                    "TariffActive": false,
                    "Supplier": {
                        "Id": 10,
                        "Name": "Panasonic Electronic Components"
                    },
                    "QuantityAvailableforPackageType": 0,
                    "MaxQuantityForDistribution": 0,
                    "MinimumOrderQuantity": 0,
                    "StandardPackage": 0,
                    "DigiReelFee": 0.0
                }
            ],
            "QuantityAvailable": 0,
            "ProductStatus": {
                "Id": 0,
                "Status": "Active"
            },
            "BackOrderNotAllowed": null,
            "NormallyStocking": null,
            "Discontinued": null,
            "EndOfLife": null,
            "Ncnr": null,
            "PrimaryVideoUrl": null,
            "Parameters": [
                {
                    "ParameterId": 3,
                    "ParameterText": "Tolerance",
                    "ParameterType": "String",
                    "ValueId": "1900",
                    "ValueText": "\u00b120%"
                },
                {
                    "ParameterId": 724,
                    "ParameterText": "ESR (Equivalent Series Resistance)",
                    "ParameterType": "String",
                    "ValueId": "1",
                    "ValueText": "-"
                }
            ],
            "BaseProductNumber": null,
            "Category": {
                "CategoryId": 3,
                "ParentId": 0,
                "Name": "Capacitors",
                "ProductCount": 0,
                "NewProductCount": 0,
                "ImageUrl": "https://www.digikey.com//media.digikey.com/Photos/Maxwell%20Technologies%20Photos/BCAP0350%20E270%20T11.JPG",
                "SeoDescription": "Capacitor products, also known as \"condensers\", are generally named and organized in reference to the dielectric material incorporated within. Along with variations in construction methods, the choice of dielectric material has strong influence on a given device's relative cost, size, parametric stability, and suitability for a particular application.",
                "ChildCategories": [
                    {
                        "CategoryId": 58,
                        "ParentId": 3,
                        "Name": "Aluminum Electrolytic Capacitors",
                        "ProductCount": 0,
                        "NewProductCount": 0,
                        "ImageUrl": "https://www.digikey.com//media.digikey.com/photos/Nichicon%20Photos/VX-Series-5x12mm.JPG",
                        "SeoDescription": "A capacitor is a passive electronic device that stores electric charge. Polarized aluminum electrolytic capacitors have an anode electrode (+) made of pure aluminum foil, electrolyte that acts as the cathode, and a thin insulating layer of aluminum oxide that acts as the dielectric. Electrolytic capacitors have higher capacitance-voltage (CV) product per unit volume than ceramic capacitors or film capacitors. Applications include audio, automotive, bypass, decoupling, and motor starting capacitors.",
                        "ChildCategories": []
                    }
                ]
            },
            "DateLastBuyChance": "0001-01-01T05:51:00+00:00",
            "ManufacturerLeadWeeks": "27",
            "ManufacturerPublicQuantity": 0,
            "Series": {
                "Id": 189,
                "Name": "NHG"
            },
            "ShippingInfo": null,
            "Classifications": null
        }
    ],
    "ProductsCount": 1,
    "ExactMatches": [
        {
            "Description": {
                "ProductDescription": "CAP ALUM 1000UF 20% 35V RADIAL",
                "DetailedDescription": "Aluminum Electrolytic Capacitors Radial, Can 2000 Hrs @ 105\u00b0C"
            },
            "Manufacturer": {
                "Id": 10,
                "Name": "Panasonic Electronic Components"
            },
            "ManufacturerProductNumber": "ECA-1VHG102",
            "UnitPrice": 1.03,
            "ProductUrl": null,
            "DatasheetUrl": null,
            "PhotoUrl": null,
            "ProductVariations": [
                {
                    "DigiKeyProductNumber": "P5555-ND",
                    "PackageType": {
                        "Id": 3,
                        "Name": "Bulk"
                    },
                    "StandardPricing": [
                        {
                            "BreakQuantity": 1,
                            "UnitPrice": 1.03,
                            "TotalPrice": 1.03
                        },
                        {
                            "BreakQuantity": 10,
                            "UnitPrice": 0.79,
                            "TotalPrice": 7.9
                        },
                        {
                            "BreakQuantity": 100,
                            "UnitPrice": 0.56,
                            "TotalPrice": 56.0
                        },
                        {
                            "BreakQuantity": 500,
                            "UnitPrice": 0.44,
                            "TotalPrice": 220.0
                        },
                        {
                            "BreakQuantity": 1000,
                            "UnitPrice": 0.38,
                            "TotalPrice": 380.0
                        },
                        {
                            "BreakQuantity": 2500,
                            "UnitPrice": 0.35,
                            "TotalPrice": 875.0
                        },
                        {
                            "BreakQuantity": 5000,
                            "UnitPrice": 0.33,
                            "TotalPrice": 1650.0
                        }
                    ],
                    "MyPricing": [
                        {
                            "BreakQuantity": 1,
                            "UnitPrice": 0.74,
                            "TotalPrice": 0.74
                        },
                        {
                            "BreakQuantity": 10,
                            "UnitPrice": 0.43,
                            "TotalPrice": 4.3
                        },
                        {
                            "BreakQuantity": 5000,
                            "UnitPrice": 0.33,
                            "TotalPrice": 1650.0
                        }
                    ],
                    "MarketPlace": false,
                    "TariffActive": false,
                    "Supplier": {
                        "Id": 10,
                        "Name": "Panasonic Electronic Components"
                    },
                    "QuantityAvailableforPackageType": 0,
                    "MaxQuantityForDistribution": 0,
                    "MinimumOrderQuantity": 0,
                    "StandardPackage": 0,
                    "DigiReelFee": 0.0
                }
            ],
            "QuantityAvailable": 0,
            "ProductStatus": {
                "Id": 0,
                "Status": "Active"
            },
            "BackOrderNotAllowed": null,
            "NormallyStocking": null,
            "Discontinued": null,
            "EndOfLife": null,
            "Ncnr": null,
            "PrimaryVideoUrl": null,
            "Parameters": [
                {
                    "ParameterId": 3,
                    "ParameterText": "Tolerance",
                    "ParameterType": "String",
                    "ValueId": "1900",
                    "ValueText": "\u00b120%"
                },
                {
                    "ParameterId": 724,
                    "ParameterText": "ESR (Equivalent Series Resistance)",
                    "ParameterType": "String",
                    "ValueId": "1",
                    "ValueText": "-"
                }
            ],
            "BaseProductNumber": null,
            "Category": {
                "CategoryId": 3,
                "ParentId": 0,
                "Name": "Capacitors",
                "ProductCount": 0,
                "NewProductCount": 0,
                "ImageUrl": "https://www.digikey.com//media.digikey.com/Photos/Maxwell%20Technologies%20Photos/BCAP0350%20E270%20T11.JPG",
                "SeoDescription": "Capacitor products, also known as \"condensers\", are generally named and organized in reference to the dielectric material incorporated within. Along with variations in construction methods, the choice of dielectric material has strong influence on a given device's relative cost, size, parametric stability, and suitability for a particular application.",
                "ChildCategories": [
                    {
                        "CategoryId": 58,
                        "ParentId": 3,
                        "Name": "Aluminum Electrolytic Capacitors",
                        "ProductCount": 0,
                        "NewProductCount": 0,
                        "ImageUrl": "https://www.digikey.com//media.digikey.com/photos/Nichicon%20Photos/VX-Series-5x12mm.JPG",
                        "SeoDescription": "A capacitor is a passive electronic device that stores electric charge. Polarized aluminum electrolytic capacitors have an anode electrode (+) made of pure aluminum foil, electrolyte that acts as the cathode, and a thin insulating layer of aluminum oxide that acts as the dielectric. Electrolytic capacitors have higher capacitance-voltage (CV) product per unit volume than ceramic capacitors or film capacitors. Applications include audio, automotive, bypass, decoupling, and motor starting capacitors.",
                        "ChildCategories": []
                    }
                ]
            },
            "DateLastBuyChance": "0001-01-01T05:51:00+00:00",
            "ManufacturerLeadWeeks": "27",
            "ManufacturerPublicQuantity": 0,
            "Series": {
                "Id": 189,
                "Name": "NHG"
            },
            "ShippingInfo": null,
            "Classifications": null
        }
    ],
    "FilterOptions": {
        "Manufacturers": [
            {
                "Id": 10,
                "Value": "Panasonic Electronic Components",
                "ProductCount": 1
            }
        ],
        "Packaging": null,
        "Status": null,
        "Series": null,
        "ParametricFilters": null,
        "TopCategories": null,
        "MarketPlaceFilters": null
    },
    "SearchLocaleUsed": null,
    "AppliedParametricFiltersDto": []
}

@mofosyne
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment