Home > Uncategorized > How to Check Polish Vehicle History Using Python and RapidAPI

How to Check Polish Vehicle History Using Python and RapidAPI

When buying a used car in Poland, one of the most important steps is verifying the vehicle’s history. Thanks to modern APIs, you can now programmatically access official vehicle registration data from the CEPiK (Central Register of Vehicles and Drivers) system. In this tutorial, we’ll show you how to use Python to check a vehicle’s complete history using the Polish Vehicle History API on RapidAPI.

What Information Can You Get?

The Polish Vehicle History API provides comprehensive data about any registered vehicle in Poland:

Technical Specifications

  • Make, model, year of manufacture
  • Engine capacity and power
  • Fuel type and emission standards
  • Weight specifications and seating capacity

Ownership History

  • Complete ownership timeline
  • Number of previous owners
  • Registration provinces
  • Corporate vs. private ownership

Technical Inspections

  • All periodic technical inspections with dates and results
  • Odometer readings at each inspection
  • Detection of rolled-back odometers

Legal Status

  • Current registration status
  • Valid insurance information
  • Stolen or withdrawn vehicle alerts

Risk Assessment

  • Accident history indicators
  • Damage reports
  • Taxi usage history
  • Odometer tampering detection

Getting Started

Prerequisites

First, install the required Python library:

pip install requests

Basic Implementation

Here’s a simple example to get you started:

import requests

# API configuration
url = "https://historia-pojazdow-polskich.p.rapidapi.com/EL6574U/YS3DD55C622039715/2002-06-04"

headers = {
    "x-rapidapi-host": "historia-pojazdow-polskich.p.rapidapi.com",
    "x-rapidapi-key": "YOUR_API_KEY_HERE"
}

# Make the request
response = requests.get(url, headers=headers)

# Check if request was successful
if response.status_code == 200:
    data = response.json()
    print("Data retrieved successfully!")
    print(data)
else:
    print(f"Error: {response.status_code}")
    print(response.text)

Advanced Implementation with Error Handling

For production use, you’ll want a more robust implementation:

import requests
import json
from typing import Optional, Dict, Any

class PolishVehicleHistoryAPI:
    def __init__(self, api_key: str):
        self.base_url = "https://historia-pojazdow-polskich.p.rapidapi.com"
        self.headers = {
            "x-rapidapi-host": "historia-pojazdow-polskich.p.rapidapi.com",
            "x-rapidapi-key": api_key
        }
    
    def check_vehicle(self, license_plate: str, vin: str, first_registration_date: str) -> Optional[Dict[Any, Any]]:
        """
        Check vehicle history
        
        Args:
            license_plate: License plate number (e.g., "EL6574U")
            vin: Vehicle identification number
            first_registration_date: Date in YYYY-MM-DD format
            
        Returns:
            Dictionary with vehicle data or None on error
        """
        url = f"{self.base_url}/{license_plate}/{vin}/{first_registration_date}"
        
        try:
            response = requests.get(url, headers=self.headers, timeout=10)
            
            if response.status_code == 200:
                return response.json()
            elif response.status_code == 404:
                print("Vehicle not found with provided parameters")
                return None
            elif response.status_code == 429:
                print("API rate limit exceeded")
                return None
            else:
                print(f"API error: {response.status_code} - {response.text}")
                return None
                
        except requests.exceptions.Timeout:
            print("Timeout - API not responding")
            return None
        except requests.exceptions.RequestException as e:
            print(f"Connection error: {e}")
            return None

def main():
    # IMPORTANT: Insert your RapidAPI key here
    API_KEY = "YOUR_API_KEY_HERE"
    
    # Create API instance
    api = PolishVehicleHistoryAPI(API_KEY)
    
    # Vehicle parameters
    license_plate = "EL6574U"
    vin = "YS3DD55C622039715"
    registration_date = "2002-06-04"
    
    print(f"Checking vehicle: {license_plate}")
    
    # Retrieve data
    data = api.check_vehicle(license_plate, vin, registration_date)
    
    if data:
        print("\n=== VEHICLE HISTORY RESULTS ===")
        
        # Display basic information
        if len(data) > 0 and "technicalData" in data[0]:
            basic_data = data[0]["technicalData"]["basicData"]
            print(f"Make: {basic_data.get('make')}")
            print(f"Model: {basic_data.get('model')}")
            print(f"Year: {basic_data.get('yearOfManufacture')}")
            print(f"Registration status: {basic_data.get('registrationStatus')}")
            
            # Odometer reading
            if basic_data.get('odometerReadings'):
                reading = basic_data['odometerReadings'][0]
                rolled_back = " (ODOMETER ROLLED BACK!)" if reading.get('rolledBack') else ""
                print(f"Mileage: {reading.get('value')} {reading.get('unit')}{rolled_back}")
        
        # Risk analysis (if available)
        if len(data) > 2 and "carfaxData" in data[2]:
            risk = data[2]["carfaxData"]["risk"]
            print("\n=== RISK ANALYSIS ===")
            print(f"Stolen: {'YES' if risk.get('stolen') else 'NO'}")
            print(f"Post-accident: {'YES' if risk.get('postAccident') else 'NO'}")
            print(f"Odometer tampering: {'YES' if risk.get('odometerTampering') else 'NO'}")
            print(f"Taxi: {'YES' if risk.get('taxi') else 'NO'}")
        
        # Save complete data to file
        with open(f"vehicle_history_{license_plate}.json", "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        print(f"\nComplete data saved to: vehicle_history_{license_plate}.json")
    
    else:
        print("Failed to retrieve vehicle data")

if __name__ == "__main__":
    main()

Understanding the API Response

The API returns data in three main sections:

1. Technical Data

Contains all technical specifications and current vehicle status:

technical_data = data[0]["technicalData"]["basicData"]
print(f"Make: {technical_data['make']}")
print(f"Model: {technical_data['model']}")
print(f"Engine capacity: {technical_data['engineCapacity']} cc")

2. Timeline Data

Provides complete ownership and inspection history:

timeline = data[1]["timelineData"]
print(f"Total owners: {timeline['totalOwners']}")
print(f"Current registration province: {timeline['registrationProvince']}")

# Loop through all events
for event in timeline["events"]:
    print(f"{event['eventDate']}: {event['eventName']}")

3. Risk Assessment

Carfax-style risk indicators:

risk_data = data[2]["carfaxData"]["risk"]
if risk_data["odometerTampering"]:
    print("⚠️ Warning: Possible odometer tampering detected!")

Real-World Use Cases

1. Used Car Marketplace Integration

def evaluate_vehicle_for_listing(license_plate, vin, registration_date):
    api = PolishVehicleHistoryAPI("YOUR_API_KEY")
    data = api.check_vehicle(license_plate, vin, registration_date)
    
    if not data:
        return {"status": "error", "message": "Cannot verify vehicle"}
    
    # Extract risk factors
    risk = data[2]["carfaxData"]["risk"] if len(data) > 2 else {}
    
    risk_score = sum([
        risk.get("stolen", False),
        risk.get("postAccident", False), 
        risk.get("odometerTampering", False),
        risk.get("taxi", False)
    ])
    
    return {
        "status": "success",
        "risk_level": "high" if risk_score > 1 else "low",
        "owners_count": data[1]["timelineData"]["totalOwners"],
        "mileage_verified": not data[0]["technicalData"]["basicData"]["odometerReadings"][0]["rolledBack"]
    }

2. Insurance Risk Assessment

def calculate_insurance_risk(vehicle_data):
    if not vehicle_data:
        return "unknown"
    
    timeline = vehicle_data[1]["timelineData"]
    risk_data = vehicle_data[2]["carfaxData"]["risk"]
    
    # High risk indicators
    if (timeline["totalOwners"] > 5 or 
        risk_data.get("postAccident") or 
        risk_data.get("taxi")):
        return "high_risk"
    
    return "standard_risk"

Getting Your API Key

  1. Sign up at RapidAPI.com
  2. Search for “Polish Vehicle History” or “Historia Pojazdów Polskich”
  3. Subscribe to an appropriate plan
  4. Copy your API key from the “Headers” section
  5. Replace "YOUR_API_KEY_HERE" with your actual key

API Parameters Explained

The API endpoint requires three parameters:

  • license_plate: The Polish license plate number (e.g., “EL6574U”)
  • vin: The 17-character Vehicle Identification Number
  • first_registration_date: Date when the vehicle was first registered in Poland (YYYY-MM-DD format)

Best Practices and Security

1. Secure API Key Management

Never hardcode your API key. Use environment variables instead:

import os

API_KEY = os.environ.get('RAPIDAPI_KEY')
if not API_KEY:
    raise ValueError("Please set RAPIDAPI_KEY environment variable")

2. Rate Limiting and Caching

Implement proper rate limiting to avoid exceeding API quotas:

import time
from functools import wraps

def rate_limit(max_calls_per_minute=60):
    min_interval = 60.0 / max_calls_per_minute
    last_called = [0.0]
    
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            elapsed = time.time() - last_called[0]
            left_to_wait = min_interval - elapsed
            if left_to_wait > 0:
                time.sleep(left_to_wait)
            ret = func(*args, **kwargs)
            last_called[0] = time.time()
            return ret
        return wrapper
    return decorator

@rate_limit(max_calls_per_minute=50)
def check_vehicle_with_rate_limit(api, license_plate, vin, date):
    return api.check_vehicle(license_plate, vin, date)

3. Error Handling and Retries

Implement exponential backoff for transient errors:

import time
import random

def check_vehicle_with_retry(api, license_plate, vin, date, max_retries=3):
    for attempt in range(max_retries):
        try:
            result = api.check_vehicle(license_plate, vin, date)
            if result is not None:
                return result
        except requests.exceptions.RequestException:
            if attempt < max_retries - 1:
                wait_time = (2 ** attempt) + random.random()
                time.sleep(wait_time)
            else:
                raise
    
    return None

Conclusion

The Polish Vehicle History API provides a powerful way to programmatically access comprehensive vehicle data directly from official government sources. Whether you’re building a used car marketplace, developing an insurance application, or creating tools for automotive professionals, this API offers reliable and up-to-date information about any vehicle registered in Poland.

The examples in this guide provide a solid foundation for integrating vehicle history checks into your Python applications. Remember to handle errors gracefully, respect rate limits, and keep your API credentials secure.

With this integration, you can help users make informed decisions when buying used cars, reduce fraud in automotive transactions, and build more trustworthy platforms for the Polish automotive market.
https://www.tablicarejestracyjnaapi.pl/

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment