Skip to main content

Authentication

Trading Card API uses OAuth 2.0 with the client credentials flow for secure API access. This guide will walk you through setting up authentication for your application.

🔐 Authentication Overview

Our authentication system is designed to be secure, scalable, and easy to implement:

  • OAuth 2.0 Client Credentials Flow - Industry standard for server-to-server authentication
  • Bearer Token Authentication - Include tokens in request headers
  • Token Expiration - Tokens expire for security (typically 24 hours)
  • Automatic Refresh - Seamlessly refresh tokens as needed

📝 Step 1: Create an Account

  1. Visit api.tradingcardapi.com/register
  2. Fill out the registration form with your details
  3. Verify your email address
  4. Log in to your new account

🔑 Step 2: Create an Application

Once logged in, create an application to get your credentials:

  1. Navigate to Applications in your dashboard
  2. Click Create New Application
  3. Fill out the application details:
    • Name: Your application name
    • Description: Brief description of your app
    • Type: Choose "Machine-to-Machine" for server applications
  4. Save your application

You'll receive:

  • Client ID: Public identifier for your application
  • Client Secret: Private key (keep this secure!)
Keep Your Credentials Safe

Never expose your client secret in client-side code or public repositories. Store it securely as an environment variable.

🎫 Step 3: Get an Access Token

Use the client credentials flow to obtain an access token:

HTTP Request

POST https://api.tradingcardapi.com/oauth/token
Content-Type: application/json

{
"grant_type": "client_credentials",
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"scope": "read write"
}

cURL Example

curl -X POST "https://api.tradingcardapi.com/oauth/token" \
-H "Content-Type: application/json" \
-d '{
"grant_type": "client_credentials",
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"scope": "read write"
}'

Response

{
"token_type": "Bearer",
"expires_in": 86400,
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
"scope": "read write"
}

🚀 Step 4: Make Authenticated Requests

Include the access token in the Authorization header of your API requests:

GET https://api.tradingcardapi.com/cards
Authorization: Bearer your_access_token
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json

💻 Code Examples

PHP

<?php

class TradingCardAPI {
private $clientId;
private $clientSecret;
private $accessToken;
private $baseUrl = 'https://api.tradingcardapi.com';

public function __construct($clientId, $clientSecret) {
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
}

public function authenticate() {
$response = $this->request('POST', '/oauth/token', [
'grant_type' => 'client_credentials',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'scope' => 'read write'
]);

$this->accessToken = $response['access_token'];
return $this->accessToken;
}

public function getCards($params = []) {
return $this->request('GET', '/cards', $params);
}

private function request($method, $endpoint, $data = []) {
$url = $this->baseUrl . $endpoint;
$headers = [
'Accept: application/vnd.api+json',
'Content-Type: application/json'
];

if ($this->accessToken) {
$headers[] = 'Authorization: Bearer ' . $this->accessToken;
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
} elseif ($method === 'GET' && !empty($data)) {
$url .= '?' . http_build_query($data);
curl_setopt($ch, CURLOPT_URL, $url);
}

$response = curl_exec($ch);
curl_close($ch);

return json_decode($response, true);
}
}

// Usage
$api = new TradingCardAPI('your_client_id', 'your_client_secret');
$api->authenticate();
$cards = $api->getCards(['page[limit]' => 10]);

JavaScript (Node.js)

const axios = require('axios');

class TradingCardAPI {
constructor(clientId, clientSecret) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.baseUrl = 'https://api.tradingcardapi.com';
this.accessToken = null;
}

async authenticate() {
try {
const response = await axios.post(`${this.baseUrl}/oauth/token`, {
grant_type: 'client_credentials',
client_id: this.clientId,
client_secret: this.clientSecret,
scope: 'read write'
});

this.accessToken = response.data.access_token;
return this.accessToken;
} catch (error) {
throw new Error(`Authentication failed: ${error.response.data.message}`);
}
}

async getCards(params = {}) {
return this.request('GET', '/cards', params);
}

async request(method, endpoint, params = {}) {
const headers = {
'Accept': 'application/vnd.api+json',
'Content-Type': 'application/json'
};

if (this.accessToken) {
headers['Authorization'] = `Bearer ${this.accessToken}`;
}

try {
const config = {
method,
url: `${this.baseUrl}${endpoint}`,
headers
};

if (method === 'GET') {
config.params = params;
} else {
config.data = params;
}

const response = await axios(config);
return response.data;
} catch (error) {
throw new Error(`API request failed: ${error.response.data.message}`);
}
}
}

// Usage
async function example() {
const api = new TradingCardAPI('your_client_id', 'your_client_secret');
await api.authenticate();
const cards = await api.getCards({ 'page[limit]': 10 });
console.log(cards);
}

Python

import requests
import json

class TradingCardAPI:
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
self.base_url = 'https://api.tradingcardapi.com'
self.access_token = None

def authenticate(self):
url = f"{self.base_url}/oauth/token"
data = {
'grant_type': 'client_credentials',
'client_id': self.client_id,
'client_secret': self.client_secret,
'scope': 'read write'
}

response = requests.post(url, json=data)
response.raise_for_status()

token_data = response.json()
self.access_token = token_data['access_token']
return self.access_token

def get_cards(self, params=None):
return self.request('GET', '/cards', params)

def request(self, method, endpoint, params=None):
url = f"{self.base_url}{endpoint}"
headers = {
'Accept': 'application/vnd.api+json',
'Content-Type': 'application/json'
}

if self.access_token:
headers['Authorization'] = f'Bearer {self.access_token}'

if method == 'GET':
response = requests.get(url, headers=headers, params=params)
else:
response = requests.post(url, headers=headers, json=params)

response.raise_for_status()
return response.json()

# Usage
api = TradingCardAPI('your_client_id', 'your_client_secret')
api.authenticate()
cards = api.get_cards({'page[limit]': 10})
print(cards)

🔄 Token Management

Token Expiration

Access tokens typically expire after 24 hours. When a token expires, you'll receive a 401 Unauthorized response.

Automatic Refresh

Implement automatic token refresh in your application:

async function makeAuthenticatedRequest(api, endpoint, params) {
try {
return await api.request('GET', endpoint, params);
} catch (error) {
if (error.response && error.response.status === 401) {
// Token expired, refresh and retry
await api.authenticate();
return await api.request('GET', endpoint, params);
}
throw error;
}
}

🔒 Security Best Practices

Environment Variables

Store credentials as environment variables:

# .env file
TRADING_CARD_API_CLIENT_ID=your_client_id
TRADING_CARD_API_CLIENT_SECRET=your_client_secret
// Load from environment
const clientId = process.env.TRADING_CARD_API_CLIENT_ID;
const clientSecret = process.env.TRADING_CARD_API_CLIENT_SECRET;

Token Storage

  • Server-side: Store tokens in memory or secure cache (Redis)
  • Never store tokens in client-side code or local storage
  • Rotate credentials periodically for enhanced security

Rate Limiting

  • Implement exponential backoff for rate limit responses
  • Cache responses to reduce API calls
  • Monitor usage to stay within limits

❌ Common Issues

Invalid Client Credentials

{
"error": "invalid_client",
"error_description": "Client authentication failed"
}

Solution: Verify your client ID and secret are correct.

Expired Token

{
"error": "invalid_token",
"error_description": "The access token provided is expired"
}

Solution: Request a new token using the authentication flow.

Insufficient Scope

{
"error": "insufficient_scope",
"error_description": "The request requires higher privileges"
}

Solution: Request appropriate scopes when getting your token.

🚀 Next Steps

Now that you have authentication set up:

  1. Make your first request →
  2. Learn about JSON:API responses →
  3. Explore available endpoints →

💡 Testing Your Setup

Use this quick test to verify your authentication:

# 1. Get a token
curl -X POST "https://api.tradingcardapi.com/oauth/token" \
-H "Content-Type: application/json" \
-d '{"grant_type":"client_credentials","client_id":"YOUR_ID","client_secret":"YOUR_SECRET","scope":"read"}'

# 2. Test the token
curl -X GET "https://api.tradingcardapi.com/cards?page[limit]=1" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Accept: application/vnd.api+json"

If you see card data in the response, your authentication is working correctly!