npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

autotrader-connect-api

v1.0.0

Published

Production-ready TypeScript wrapper for Auto Trader UK Connect APIs

Readme

autotrader-connect-api

NPM Version Build Status Coverage Status TypeScript License: MIT

A production-ready TypeScript wrapper for the Auto Trader UK Connect APIs. This package provides a comprehensive, type-safe interface to interact with AutoTrader's vehicle data, stock management, search, and other automotive services.

Features

  • 🚀 Production Ready: Built with enterprise-grade error handling, retry logic, and rate limiting
  • 🔒 Type Safe: Full TypeScript support with comprehensive type definitions
  • 🔐 Secure Authentication: Automatic OAuth2 token management with refresh capabilities
  • Performance Optimized: Built-in rate limiting and request batching
  • 🛡️ Robust Error Handling: Comprehensive error types and retry strategies
  • 📊 Rich Data Models: Extensive type definitions for all API responses
  • 🧪 Well Tested: High test coverage with unit and integration tests
  • 📚 Comprehensive Documentation: Full API documentation with examples

Table of Contents

Installation

npm install autotrader-connect-api

Or with yarn:

yarn add autotrader-connect-api

Quick Start

import { initializeClient, getVehicle, searchVehicles } from 'autotrader-connect-api';

// Initialize the client
const client = initializeClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
  baseURL: 'https://api.autotrader.co.uk', // optional
});

// Search for vehicles
const vehicles = await searchVehicles({
  make: 'BMW',
  model: '3 Series',
  priceRange: { min: 15000, max: 30000 },
  yearRange: { min: 2018 },
  postcode: 'SW1A 1AA',
  radius: 50,
});

console.log(`Found ${vehicles.data.length} vehicles`);

// Get a specific vehicle
const vehicle = await getVehicle('ABC123', 12345);
console.log(`Vehicle: ${vehicle.make} ${vehicle.model} - £${vehicle.price}`);

🧪 Sandbox Environment Support

The package includes comprehensive sandbox support for testing and development. The API automatically detects your environment and switches between sandbox and production endpoints.

Environment Detection

  • Development: NODE_ENV=development → Uses sandbox automatically
  • Test: NODE_ENV=test → Uses sandbox automatically
  • Production: NODE_ENV=production → Uses production API
  • Manual Override: AT_USE_SANDBOX=true/false → Explicit control

Environment Variables

# Production API
AT_BASE_URL=https://api.autotrader.co.uk
AT_API_KEY=your_production_key
AT_API_SECRET=your_production_secret

# Sandbox API
AT_SANDBOX_BASE_URL=https://sandbox-api.autotrader.co.uk
AT_SANDBOX_API_KEY=your_sandbox_key
AT_SANDBOX_API_SECRET=your_sandbox_secret

# Environment control
NODE_ENV=development
AT_USE_SANDBOX=true

Quick Setup Methods

import { quickSetup, setupSandbox, setupProduction } from 'autotrader-connect-api';

// 1. Automatic environment detection
const client = quickSetup(); // Uses sandbox in development, production otherwise

// 2. Force sandbox mode
const sandboxClient = setupSandbox(); // Always uses sandbox

// 3. Force production mode  
const prodClient = setupProduction(); // Always uses production

// 4. Override environment detection
const testClient = quickSetup({ 
  forceSandbox: true // Force sandbox regardless of NODE_ENV
});

Explicit Configuration

import { initializeClient } from 'autotrader-connect-api';

// Sandbox configuration
const sandboxClient = initializeClient({
  apiKey: 'sandbox-key',
  apiSecret: 'sandbox-secret',
  baseURL: 'https://sandbox-api.autotrader.co.uk',
  useSandbox: true,
  debug: true // Helpful for development
});

// Production configuration
const prodClient = initializeClient({
  apiKey: 'prod-key',
  apiSecret: 'prod-secret',
  baseURL: 'https://api.autotrader.co.uk',
  useSandbox: false,
  debug: false
});

Testing Best Practices

// In your test files
import { setupSandbox } from 'autotrader-connect-api';

describe('Vehicle API Tests', () => {
  let client;
  
  beforeAll(() => {
    // Always use sandbox for tests
    client = setupSandbox({
      debug: true // See all API calls in test output
    });
  });
  
  it('should search for vehicles', async () => {
    const results = await searchVehicles({ make: 'BMW' });
    expect(results.data).toBeDefined();
  });
});

Development Workflow

// .env.development
NODE_ENV=development
AT_SANDBOX_API_KEY=your_dev_key
AT_SANDBOX_API_SECRET=your_dev_secret
AT_USE_SANDBOX=true
AT_DEBUG=true

// .env.production  
NODE_ENV=production
AT_API_KEY=your_prod_key
AT_API_SECRET=your_prod_secret
AT_USE_SANDBOX=false
AT_DEBUG=false

Sandbox Features

✅ Automatic environment detection
✅ Separate credentials for sandbox vs production
✅ Debug mode enabled by default in sandbox
✅ Same API interface as production
✅ Perfect for CI/CD testing pipelines
✅ No accidental production API calls during development

🏢 Advertiser ID Management

The package now includes comprehensive advertiser ID support for proper multi-tenant operations:

Key Features

Consistent Advertiser Context: Use advertiserId (number) throughout the API
Legacy Support: Backward compatible with dealerId (string)
Advertiser-Scoped Clients: Automatic advertiser context injection
Validation Utilities: Verify advertiser IDs before API calls
Multi-Advertiser Support: Manage multiple dealers in one application
Comprehensive Advertiser Management: Full CRUD operations for advertiser data

Quick Examples

import { 
  getVehicle, 
  searchVehicles, 
  createAdvertiserClient,
  getCurrentAdvertiser 
} from 'autotrader-connect-api';

// Get vehicle with advertiser context
const vehicle = await getVehicle('ABC123', 12345);
console.log(`Vehicle from ${vehicle.advertiser.name}`);

// Search with advertiser filtering
const results = await searchVehicles({
  make: 'BMW',
  advertiserId: [12345, 67890], // Multiple advertisers
  priceRange: { min: 15000, max: 30000 }
});

// Create advertiser-scoped client
const dealerClient = createAdvertiserClient(12345);
// All requests now include advertiser context automatically

// Get current advertiser information  
const advertiser = await getCurrentAdvertiser();
console.log(`Logged in as: ${advertiser.name} (ID: ${advertiser.id})`);

For comprehensive examples, see advertiser-examples.md.

Configuration

Environment Variables

Create a .env file in your project root:

# Required
AT_API_KEY=your_autotrader_api_key
AT_API_SECRET=your_autotrader_api_secret

# Optional
AT_BASE_URL=https://api.autotrader.co.uk
AT_TIMEOUT=30000
AT_RATE_LIMIT_REQUESTS=100
AT_RATE_LIMIT_WINDOW=60000
AT_DEBUG=false

Programmatic Configuration

import { initializeClient } from 'autotrader-connect-api';

const client = initializeClient({
  apiKey: process.env.AT_API_KEY!,
  apiSecret: process.env.AT_API_SECRET!,
  baseURL: 'https://api.autotrader.co.uk',
  timeout: 30000,
  maxRetries: 3,
  rateLimitRequests: 100,
  rateLimitWindow: 60000,
  debug: false,
});

Quick Setup (Environment-based)

import { quickSetup } from 'autotrader-connect-api';

// Uses environment variables automatically
const client = quickSetup({
  debug: process.env.NODE_ENV === 'development',
  timeout: 30000,
});

Authentication

The package handles OAuth2 authentication automatically:

import { getToken, getAuthManager } from 'autotrader-connect-api';

// Get current token (automatically refreshes if needed)
const token = await getToken();

// Manual auth management
const authManager = getAuthManager();
const isAuthenticated = authManager.isAuthenticated();
const authState = authManager.getAuthState();

// Force token refresh
await authManager.refreshToken();

// Clear cached token
authManager.clearToken();

API Modules

Vehicles

import { 
  getVehicle, 
  getVehicleById, 
  searchVehicles, 
  getFeaturedVehicles,
  getSimilarVehicles,
  getVehicleSpecifications 
} from 'autotrader-connect-api';

// Get vehicle by registration and advertiser ID
const vehicle = await getVehicle('ABC123', 12345);

// Get vehicle by ID
const vehicle = await getVehicleById('vehicle-id');

// Search vehicles with comprehensive filters
const results = await searchVehicles({
  make: ['BMW', 'Audi'],
  bodyType: ['Hatchback', 'Saloon'],
  fuelType: ['Petrol', 'Hybrid'],
  priceRange: { min: 15000, max: 40000 },
  yearRange: { min: 2018 },
  mileageRange: { max: 50000 },
  postcode: 'M1 1AA',
  radius: 25,
  sortBy: 'price',
  sortOrder: 'asc',
});

// Get featured vehicles
const featured = await getFeaturedVehicles(10);

// Get similar vehicles
const similar = await getSimilarVehicles('vehicle-id', 5);

// Get detailed specifications
const specs = await getVehicleSpecifications('vehicle-id');

Stock Management

import { 
  searchStock, 
  createStock, 
  updateStock, 
  publishStock,
  getStockStatistics 
} from 'autotrader-connect-api';

// Search stock with filters
const stock = await searchStock({
  status: ['Available', 'Reserved'],
  make: 'BMW',
  siteId: 'site-123',
  minDaysInStock: 7,
  sortBy: 'stockedDate',
});

// Create new stock item
const newStock = await createStock({
  make: 'BMW',
  model: '3 Series',
  year: 2020,
  mileage: 25000,
  fuelType: 'Petrol',
  transmission: 'Automatic',
  bodyType: 'Saloon',
  doors: 4,
  seats: 5,
  colour: 'Black',
  retailPrice: 25000,
  description: 'Excellent condition BMW 3 Series',
});

// Update stock item
const updated = await updateStock('stock-id', {
  retailPrice: 24000,
  status: 'Available',
});

// Publish stock to AutoTrader
const result = await publishStock(['stock-id-1', 'stock-id-2']);

// Get stock statistics
const stats = await getStockStatistics({
  siteId: 'site-123',
  dateFrom: '2024-01-01',
});

Search & Discovery

import { 
  searchVehicles, 
  quickSearch, 
  saveSearch, 
  compareVehicles,
  getPopularSearches 
} from 'autotrader-connect-api';

// Enhanced search with facets
const searchResults = await searchVehicles({
  make: 'BMW',
  priceRange: { min: 20000, max: 40000 },
  includeFacets: true,
  includeMarketInsights: true,
});

// Quick search for autocomplete
const quick = await quickSearch({
  query: 'BMW 3 Series',
  postcode: 'M1 1AA',
  maxPrice: 30000,
  limit: 5,
});

// Save search for alerts
const savedSearch = await saveSearch({
  name: 'My BMW Search',
  filters: { make: 'BMW', priceRange: { max: 30000 } },
  alertSettings: {
    enabled: true,
    frequency: 'Daily',
    email: '[email protected]',
  },
});

// Compare multiple vehicles
const comparison = await compareVehicles(['vehicle-1', 'vehicle-2', 'vehicle-3']);

// Get popular searches
const popular = await getPopularSearches('Make');

Valuations

import { 
  getValuation, 
  getQuickValuation, 
  getBatchValuations,
  getHistoricalValuation 
} from 'autotrader-connect-api';

// Get vehicle valuation
const valuation = await getValuation({
  make: 'BMW',
  model: '3 Series',
  year: 2020,
  mileage: 25000,
  condition: 'Good',
  postcode: 'M1 1AA',
});

// Quick valuation by registration
const quickVal = await getQuickValuation('ABC123', 25000, 'M1 1AA');

// Batch valuations
const batchResults = await getBatchValuations([
  { make: 'BMW', model: '3 Series', year: 2020, mileage: 25000 },
  { make: 'Audi', model: 'A4', year: 2019, mileage: 30000 },
]);

// Historical valuation data
const historical = await getHistoricalValuation({
  make: 'BMW',
  model: '3 Series',
  year: 2020,
  mileage: 25000,
}, '1y');

Taxonomy

import { 
  getVehicleMakes, 
  getVehicleModels, 
  getBodyTypes,
  searchTaxonomy 
} from 'autotrader-connect-api';

// Get all vehicle makes
const makes = await getVehicleMakes();

// Get models for a make
const models = await getVehicleModels('bmw');

// Get body types
const bodyTypes = await getBodyTypes();

// Search taxonomy
const results = await searchTaxonomy('BMW 3', 'all');

Usage Examples

Next.js API Route

// pages/api/vehicles/search.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { searchVehicles } from 'autotrader-connect-api';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const { make, model, maxPrice } = req.query;
    
    const vehicles = await searchVehicles({
      make: make as string,
      model: model as string,
      priceRange: maxPrice ? { max: Number(maxPrice) } : undefined,
    });
    
    res.status(200).json(vehicles);
  } catch (error) {
    console.error('Search error:', error);
    res.status(500).json({ error: 'Failed to search vehicles' });
  }
}

React Component with SWR

// components/VehicleSearch.tsx
import useSWR from 'swr';
import { VehicleSearchParams } from 'autotrader-connect-api';

const fetcher = (url: string) => fetch(url).then(r => r.json());

export function VehicleSearch({ filters }: { filters: VehicleSearchParams }) {
  const { data, error, isLoading } = useSWR(
    `/api/vehicles/search?${new URLSearchParams(filters)}`,
    fetcher
  );

  if (error) return <div>Error loading vehicles</div>;
  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      {data?.data?.map((vehicle: any) => (
        <div key={vehicle.id}>
          <h3>{vehicle.make} {vehicle.model}</h3>
          <p>£{vehicle.price.toLocaleString()}</p>
        </div>
      ))}
    </div>
  );
}

Express.js Server

import express from 'express';
import { quickSetup, searchVehicles } from 'autotrader-connect-api';

const app = express();
const client = quickSetup();

app.get('/api/vehicles', async (req, res) => {
  try {
    const vehicles = await searchVehicles(req.query);
    res.json(vehicles);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000);

Error Handling

The package provides comprehensive error handling:

import { searchVehicles } from 'autotrader-connect-api';

try {
  const vehicles = await searchVehicles({ make: 'BMW' });
} catch (error) {
  if (error.status === 401) {
    console.error('Authentication failed');
  } else if (error.status === 429) {
    console.error('Rate limit exceeded');
  } else if (error.status >= 500) {
    console.error('Server error');
  } else {
    console.error('Request failed:', error.message);
  }
}

Health Check

import { healthCheck } from 'autotrader-connect-api';

const health = await healthCheck();
console.log('API Health:', health);
// {
//   status: 'healthy',
//   timestamp: '2024-01-01T12:00:00Z',
//   version: '1.0.0',
//   auth: true,
//   latency: 145
// }

Rate Limiting

The package includes built-in rate limiting:

import { getClient } from 'autotrader-connect-api';

const client = getClient();

// Check rate limit status
const status = client.getRateLimitStatus();
console.log('Rate limit status:', status);
// {
//   reservoir: 95,    // requests remaining
//   running: 2,       // requests in progress
//   queued: 0         // requests queued
// }

Testing

Run the test suite:

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

# Run linting
npm run lint

# Fix linting issues
npm run lint:fix

Writing Tests

import { getVehicle } from 'autotrader-connect-api';

// Mock the client for testing
jest.mock('autotrader-connect-api', () => ({
  getVehicle: jest.fn(),
}));

test('should fetch vehicle data', async () => {
  const mockVehicle = { id: '123', make: 'BMW', model: '3 Series' };
  (getVehicle as jest.Mock).mockResolvedValue(mockVehicle);

  const result = await getVehicle('ABC123', 12345);
  expect(result).toEqual(mockVehicle);
});

Next.js Integration

App Router (Recommended)

// app/api/vehicles/route.ts
import { searchVehicles } from 'autotrader-connect-api';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  
  try {
    const vehicles = await searchVehicles({
      make: searchParams.get('make') || undefined,
      model: searchParams.get('model') || undefined,
    });
    
    return Response.json(vehicles);
  } catch (error) {
    return Response.json(
      { error: 'Failed to search vehicles' },
      { status: 500 }
    );
  }
}

Server Component

// app/vehicles/page.tsx
import { searchVehicles } from 'autotrader-connect-api';

export default async function VehiclesPage() {
  const vehicles = await searchVehicles({ make: 'BMW' });
  
  return (
    <div>
      <h1>BMW Vehicles</h1>
      {vehicles.data.map(vehicle => (
        <div key={vehicle.id}>
          <h3>{vehicle.make} {vehicle.model}</h3>
          <p>£{vehicle.price.toLocaleString()}</p>
        </div>
      ))}
    </div>
  );
}

API Reference

For complete API documentation, see the TypeDoc generated documentation.

Core Types

// Import types for use in your application
import type {
  Vehicle,
  VehicleSearchParams,
  VehicleResponse,
  StockItem,
  SearchResponse,
  ValuationResponse,
  ApiResponse,
  PaginatedResponse,
} from 'autotrader-connect-api';

Building and Publishing

Development

# Install dependencies
npm install

# Run in development mode
npm run dev

# Build the package
npm run build

# Generate documentation
npm run docs

Publishing

# Version bump (patch, minor, or major)
npm version patch

# Build and test before publishing
npm run prepublishOnly

# Publish to NPM
npm publish

# Or publish with tag
npm publish --tag beta

Automated Publishing

The package includes GitHub Actions for automated publishing:

  1. Create a release tag: git tag v1.0.1
  2. Push the tag: git push origin v1.0.1
  3. GitHub Actions will automatically build, test, and publish

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature
  3. Make your changes and add tests
  4. Ensure tests pass: npm test
  5. Commit your changes: git commit -am 'Add your feature'
  6. Push to the branch: git push origin feature/your-feature
  7. Submit a pull request

Development Guidelines

  • Follow the existing code style
  • Add tests for new features
  • Update documentation as needed
  • Ensure all tests pass
  • Follow semantic versioning

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Changelog

See CHANGELOG.md for release history.


Made with ❤️ by Your Organization