Building a Cardboard Empire: Introduction to the TCGplayer API using Python
By: Eric Kleppen
Tags: Analytics, Data Science, Programming, Business, Api Development

A Life of Cardboard

I’ve been into card games almost my entire life and started playing Magic: The Gathering (MTG) around 2nd grade in the mid 90’s. Although it wasn’t really a hobby that made me popular with girls, I stuck with it on and off and spent many Friday nights at card shops grinding constructed tournaments and booster drafts during my teenage years. Now that I’m into programming and data science, I was excited to learn the online card game marketplace, TCGplayer.com has a free API.

This article walks you through how to connect and search the TCGplayer API using Python and the Requests Library. Complete Code can be found at the bottom!

A few cards in my Magic: The Gathering Collection

Getting API Keys

TCGplayer is an internet marketplace for collectible items allowing users to set up stores through which they can sell their inventory online. API stands for Application Programming Interface.

Located at api.tcgplayer.com, the TCGplayer API is a RESTful API application that interacts with the TCGplayer store site. A large number of endpoints exist that return all aspects of the catalog, find pricing information, and manage personal stores. — https://docs.tcgplayer.com/docs/welcome

To access their API, first fill out their application form:

Accessing the API with Requests using Python

Once your paperwork is accepted, a representative from TCGplayer will email you an Application Id, Public Key, and Private Key. Using the keys, it is possible to create a connection to the API using the Requests library in Python. Use Pip to install Requests as needed:

python -m pip install requests

File config.py & Managing API Keys

This project uses API keys. If you’re new to managing your keys, make sure to save them into a config.py file instead of hard-coding them in your app. API keys can be very valuable and must be protected. Add the config file to your gitignore file to prevent it from being pushed to your repo too!

Using your Keys

The Public Key and the Private Key are needed to create a Bearer Token. A Bearer Token basically tells the system to give access to whatever holds the token. It is generated by the Authentication server automatically.

#import dependencies

import requests #pull in api keys from config file

from config import public_key, private_key

response = requests.post(

"



headers={

"Content-Type": "application/json",

"Accept": "application/json"},



data=(f"grant_type=client_credentials"

f"&client_id={public_key}&"

f"client_secret={private_key}")

) #construct api requestresponse = requests. https://api.tcgplayer.com/token ",={"Content-Type": "application/json","Accept": "application/json"},=(f"grant_type=client_credentials"f"&client_id={}&"f"client_secret={}")

Notice I use a POST request to the /token URL. I pass headers and a data payload containing the API keys into the request. The Bearer Token and metadata are returned.

Take a look at the data returned in the response using .json() or .text

response.json() #output

# {'access_token': 'YOUR_GENERATED_TOKEN',

# 'token_type': 'bearer',

# 'expires_in': 1209599,

# 'userName': 'YOUR_GENERATED_USERNAME',

# '.issued': 'Sat, 12 Sep 2020 15:40:32 GMT',

# '.expires': 'Sat, 26 Sep 2020 15:40:32 GMT'}

Notice the Bearer Token expires. TCGplayer recommends caching the metadata and only regenerating the key when it is about to expire.

Now that the Bearer Token has been generated, it can be used to interact with the API.

Save the Bearer Token to a variable:

access = response.json()['access_token']

Pass the Bearer Token into the requests Header along with the word “bearer”.

TCGplayer also wants you to include a User-Agent in the header so they can track API usage easier:

headers = {"accept": "application/json",

"Content-Type": "application/json",

'User-Agent': 'YOUR_USER_AGENT',

"Authorization": "bearer " + access}

Pick an API endpoint to interact with. I will start with the Catalog > List All Categories API endpoint and start exploring!

TCGplayer.com API endpoints

Notice the variable URL is the API endpoint I want to hit.

I pass the URL and Headers into the GET request and return the JSON response.

If I wanted to explore more about a particular category, I can use the categoryID in the URL for the API endpoint. For example, the URL below will let me search category 1 (Magic the gathering is category 1):

#search the mtg catalog https://api.tcgplayer.com/catalog/categories/1/search

While most API endpoints can be accessed with a GET request, some endpoints like Catalog > Search Category Products allow you to use a POST request to pass in filters to the request.

For example, say I want to search for the Magic: The Gathering card Tithe. I can pass a sort option, as well as filters and aggregations into the JSON payload.

url = " https://api.tcgplayer.com/catalog/categories/1/search payload = {"sort":"Relevance",

"filters": [{

"values": ["Tithe"],

"name": "productName"

}]} search_response = requests.request("POST", url, json=payload, headers=headers) search_response.json()

The request returns a list of product IDs. Depending on how the items are sorted, the list of product IDs matches how the results display on TCGplayer.com

Search_response.text for Tithe sorted by Relevance

Search Results for Tithe sorted by Relevance on TCGplayer.com

To retrieve the information about the cards in the search request, simply pass the comma separated list into the API endpoint URL.



productids = str(search_response.json()["results"]) endpoint = " https://api.tcgplayer.com/catalog/products/ productids = str(search_response.json()["results"]) url = endpoint + productids response = requests.get( url, headers=headers) response.json()

Notice I simply combine the API endpoint with the list of product IDs.

response.json()

Congratulations! You can now navigate and explore the TCGplayer API!

Final Thoughts and Code

Card games are not going anywhere and have matured into a popular niche. Magic: The Gathering has been around for nearly 30 years at this point! Using tools like the TCGplayer API, there is a unique opportunity for some data analysis and data science to take place and develop new tools and apps to help players build and manage their collections. Through the TCGplayer API, it is even possible to run your online store!

If you enjoyed this article, check out my others on programming and data science:

Complete Code

Below is the complete Code