Annuaire d'APIs
API CarTrawler
L'api
CarTrawler
L’API CarTrawler permet de proposer la réservation de voitures de location dans plus de 50 000 lieux, en intégrant facilement des services B2B de mobilité.
CarTrawler
est disponible via
https://partner.cartrawler.com
Guide Complet sur l'API CarTrawler pour les Développeurs
Introduction à l'API CarTrawler
L'API CarTrawler est une solution puissante pour intégrer des services de location de véhicules dans vos applications. Que vous soyez un développeur indépendant ou une grande entreprise, cette API offre une flexibilité et une richesse de fonctionnalités inégalées.
Pourquoi Utiliser l'API CarTrawler ?
- Accès à un large réseau de fournisseurs de location de véhicules.
- Intégration facile avec des bibliothèques et des frameworks populaires.
- Support technique dédié et documentation complète.
Comment Intégrer l'API CarTrawler
Pour commencer à utiliser l'API CarTrawler, suivez ces étapes simples :
- Inscription sur le portail des développeurs CarTrawler.
- Obtention de votre clé API unique.
- Intégration de la clé API dans votre application.
- Utilisation des endpoints API pour effectuer des recherches et des réservations.
Exemples de Code
const axios = require('axios');
const Redis = require('redis');
class RentalcarsClient {
constructor(apiKey, options = {}) {
this.apiKey = apiKey;
this.baseURL = 'https://demandapi.booking.com/3.1/cars/';
this.timeout = options.timeout || 5000;
this.maxRetries = options.maxRetries || 3;
// Configuration Redis pour le cache
this.redis = Redis.createClient(options.redis);
// Instance axios avec intercepteurs
this.client = axios.create({
baseURL: this.baseURL,
timeout: this.timeout,
headers: {
'User-Agent': 'MyApp/1.0',
'Accept': 'application/json'
}
});
this.setupInterceptors();
}
setupInterceptors() {
// Intercepteur de requête pour ajouter la clé API
this.client.interceptors.request.use(config => {
config.params = { ...config.params, access_key: this.apiKey };
return config;
});
// Intercepteur de réponse pour la gestion d'erreurs
this.client.interceptors.response.use(
response => response,
async error => {
if (error.response?.status === 429) {
// Gestion du rate limiting
const retryAfter = error.response.headers['retry-after'] || 60;
console.warn(`Rate limit atteint. Retry dans ${retryAfter}s`);
await this.delay(retryAfter * 1000);
return this.client.request(error.config);
}
throw error;
}
);
}
async getCarDetails(carId, useCache = true) {
const cacheKey = `car:${carId}`;
try {
// Vérification du cache Redis
if (useCache) {
const cached = await this.redis.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
}
const response = await this.client.get('/cars', {
params: { car_id: carId }
});
const data = response.data;
// Mise en cache pour 5 minutes
if (useCache && data.data?.length > 0) {
await this.redis.setex(cacheKey, 300, JSON.stringify(data));
}
return data;
} catch (error) {
console.error('Erreur Rentalcars.com:', {
message: error.message,
status: error.response?.status,
data: error.response?.data
});
throw new Error(`Impossible de récupérer la voiture ${carId}: ${error.message}`);
}
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Utilisation recommandée
const client = new RentalcarsClient(process.env.RENTALCARS_API_KEY, {
timeout: 10000,
redis: { host: 'localhost', port: 6379 }
});
// Exemple avec gestion d'erreurs complète
async function trackCar(carId) {
try {
const carData = await client.getCarDetails(carId);
if (!carData.data || carData.data.length === 0) {
throw new Error(`Voiture ${carId} non trouvée`);
}
const car = carData.data[0];
console.log(`Voiture ${car.car.id}: ${car.car.status}`);
return car;
} catch (error) {
console.error('Erreur lors du suivi:', error.message);
throw error;
}
}
module.exports = { RentalcarsClient, trackCar };
import asyncio
import aiohttp
import aioredis
import json
import logging
from typing import Optional, Dict, Any
from datetime import datetime, timedelta
class RentalcarsAsyncClient:
def __init__(self, api_key: str, redis_url: str = "redis://localhost"):
self.api_key = api_key
self.base_url = "https://demandapi.booking.com/3.1/cars/"
self.redis_url = redis_url
self.session = None
self.redis = None
# Configuration du logging
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
async def __aenter__(self):
"""Initialisation du context manager"""
timeout = aiohttp.ClientTimeout(total=10)
self.session = aiohttp.ClientSession(
timeout=timeout,
headers={'User-Agent': 'Production-RentalcarsTracker/2.0'}
)
self.redis = await aioredis.from_url(self.redis_url)
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Nettoyage des ressources"""
if self.session:
await self.session.close()
if self.redis:
await self.redis.close()
async def get_car_details(
self,
car_id: str,
use_cache: bool = True,
max_retries: int = 3
) -> Dict[Any, Any]:
"""
Récupère les détails d'une voiture avec gestion du cache et retry automatique
Args:
car_id: ID de la voiture (ex: 'CAR1234')
use_cache: Utiliser le cache Redis
max_retries: Nombre maximum de tentatives
Returns:
Dict contenant les données de la voiture
Raises:
Exception: En cas d'erreur après tous les retries
"""
cache_key = f"car:{car_id}"
# Vérification du cache
if use_cache and self.redis:
try:
cached_data = await self.redis.get(cache_key)
if cached_data:
self.logger.info(f"Cache hit pour voiture {car_id}")
return json.loads(cached_data)
except Exception as e:
self.logger.warning(f"Erreur cache Redis: {e}")
# Appel API avec retry
for attempt in range(max_retries):
try:
params = {
'access_key': self.api_key,
'car_id': car_id
}
async with self.session.get(
f"{self.base_url}/cars",
params=params
) as response:
if response.status == 429:
# Rate limiting
retry_after = int(response.headers.get('Retry-After', 60))
self.logger.warning(f"Rate limit. Attente {retry_after}s")
await asyncio.sleep(retry_after)
continue
response.raise_for_status()
data = await response.json()
# Validation des données
if not data.get('data'):
raise ValueError(f"Aucune voiture trouvée pour {car_id}")
# Mise en cache (5 minutes)
if use_cache and self.redis:
try:
await self.redis.setex(
cache_key,
300,
json.dumps(data)
)
except Exception as e:
self.logger.warning(f"Erreur mise en cache: {e}")
self.logger.info(f"Voiture {car_id} récupérée avec succès")
return data
except aiohttp.ClientError as e:
self.logger.error(f"Tentative {attempt + 1} échouée: {e}")
if attempt == max_retries - 1:
raise Exception(f"Échec après {max_retries} tentatives: {e}")
await asyncio.sleep(2 ** attempt) # Backoff exponentiel
raise Exception("Nombre maximum de tentatives atteint")
# Exemple d'utilisation en production
async def monitor_cars(car_ids: list):
"""Surveille une liste de voitures de manière asynchrone"""
async with RentalcarsAsyncClient(
api_key=os.getenv('RENTALCARS_API_KEY')
) as client:
tasks = []
for car_id in car_ids:
task = client.get_car_details(car_id)
tasks.append(task)
# Exécution parallèle
results = await asyncio.gather(*tasks, return_exceptions=True)
for i, result in enumerate(results):
if isinstance(result, Exception):
print(f"Erreur pour {car_ids[i]}: {result}")
else:
car = result['data'][0]
print(f"Voiture {car['car']['id']}: {car['car_status']}")
# Utilisation
# asyncio.run(monitor_cars(['CAR1234', 'CAR5678', 'CAR9101']))
-- php --
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Exception\RequestException;
/**
* Service Rentalcars.com pour Laravel
*
* Gestion complète de l'API avec cache, retry et monitoring
*/
class RentalcarsService
{
private string $apiKey;
private string $baseUrl;
private int $timeout;
private int $maxRetries;
public function __construct()
{
$this->apiKey = config('services.rentalcars.key');
$this->baseUrl = 'https://demandapi.booking.com/3.1/cars/';
$this->timeout = config('services.rentalcars.timeout', 10);
$this->maxRetries = config('services.rentalcars.max_retries', 3);
if (empty($this->apiKey)) {
throw new \InvalidArgumentException('Clé API Rentalcars.com requise');
}
}
/**
* Récupère les détails d'une voiture avec gestion complète des erreurs
*/
public function getCarDetails(string $carId, bool $useCache = true): array
{
$cacheKey = "rentalcars.car.{$carId}";
// Vérification du cache Laravel
if ($useCache && Cache::has($cacheKey)) {
Log::info("Cache hit pour voiture {$carId}");
return Cache::get($cacheKey);
}
$attempt = 0;
$lastException = null;
while ($attempt < $this->maxRetries) {
try {
$response = Http::timeout($this->timeout)
->retry(3, 100) // 3 tentatives avec 100ms d'intervalle
->withHeaders([
'User-Agent' => 'Laravel-RentalcarsTracker/1.0',
'Accept' => 'application/json'
])
->get("{$this->baseUrl}/cars", [
'access_key' => $this->apiKey,
'car_id' => $carId
]);
if ($response->status() === 429) {
$retryAfter = $response->header('Retry-After', 60);
Log::warning("Rate limit atteint. Attente {$retryAfter}s");
sleep((int)$retryAfter);
$attempt++;
continue;
}
$response->throw(); // Lance une exception si erreur HTTP
$data = $response->json();
// Validation des données
if (empty($data['data'])) {
throw new \Exception("Aucune voiture trouvée pour {$carId}");
}
// Mise en cache pour 5 minutes
if ($useCache) {
Cache::put($cacheKey, $data, now()->addMinutes(5));
}
Log::info("Voiture {$carId} récupérée avec succès", [
'attempt' => $attempt + 1,
'cars_count' => count($data['data'])
]);
return $data;
} catch (RequestException $e) {
$lastException = $e;
$attempt++;
Log::warning("Tentative {$attempt} échouée pour voiture {$carId}", [
'error' => $e->getMessage(),
'status_code' => $e->getResponse()?->getStatusCode()
]);
if ($attempt < $this->maxRetries) {
// Backoff exponentiel
sleep(pow(2, $attempt));
}
}
}
// Toutes les tentatives ont échoué
Log::error("Échec définitif pour voiture {$carId}", [
'attempts' => $this->maxRetries,
'last_error' => $lastException?->getMessage()
]);
throw new \Exception(
"Impossible de récupérer la voiture {$carId} après {$this->maxRetries} tentatives: " .
$lastException?->getMessage()
);
}
/**
* Recherche de voitures avec filtres avancés
*/
public function searchCars(array $filters = []): array
{
$validFilters = [
'location_id', 'pickup_date', 'dropoff_date',
'car_type', 'supplier_id', 'car_id'
];
$params = array_merge(
['access_key' => $this->apiKey],
array_intersect_key($filters, array_flip($validFilters))
);
try {
$response = Http::timeout($this->timeout)
->get("{$this->baseUrl}/cars", $params);
$response->throw();
return $response->json();
} catch (RequestException $e) {
Log::error('Erreur recherche de voitures', [
'filters' => $filters,
'error' => $e->getMessage()
]);
throw $e;
}
}
/**
* Obtient les statistiques de santé de l'API
*/
public function getHealthStatus(): array
{
$startTime = microtime(true);
try {
$response = Http::timeout(5)
->get("{$this->baseUrl}/locations", [
'access_key' => $this->apiKey,
'limit' => 1
]);
$responseTime = round((microtime(true) - $startTime) * 1000);
return [
'status' => $response->successful() ? 'healthy' : 'degraded',
'response_time_ms' => $responseTime,
'http_status' => $response->status(),
'timestamp' => now()->toISOString()
];
} catch (\Exception $e) {
return [
'status' => 'unhealthy',
'error' => $e->getMessage(),
'timestamp' => now()->toISOString()
];
}
}
}
// Configuration dans config/services.php
/*
'rentalcars' => [
'key' => env('RENTALCARS_API_KEY'),
'timeout' => env('RENTALCARS_TIMEOUT', 10),
'max_retries' => env('RENTALCARS_MAX_RETRIES', 3),
],
*/
// Utilisation dans un Controller
/*
class CarController extends Controller
{
public function show(string $carId, RentalcarsService $rentalcars)
{
try {
$carData = $rentalcars->getCarDetails($carId);
return response()->json($carData);
} catch (\Exception $e) {
return response()->json([
'error' => 'Voiture non trouvée',
'message' => $e->getMessage()
], 404);
}
}
}
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Service
public class RentalcarsService {
@Value("${rentalcars.api.key}")
private String apiKey;
@Value("${rentalcars.api.url}")
private String baseUrl;
private final RestTemplate restTemplate;
@Autowired
public RentalcarsService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Cacheable(value = "carCache", key = "#carId")
@Retryable(value = {HttpClientErrorException.TooManyRequests.class},
maxAttempts = 3,
backoff = @Backoff(delay = 1000, multiplier = 2))
public Map getCarDetails(String carId) {
String url = baseUrl + "/cars?car_id={carId}&access_key={apiKey}";
HttpHeaders headers = new HttpHeaders();
headers.set("User-Agent", "Java-RentalcarsTracker/1.0");
Map params = new HashMap<>();
params.put("carId", carId);
params.put("apiKey", apiKey);
ResponseEntity
require 'faraday'
require 'faraday_middleware'
require 'redis'
require 'json'
class RentalcarsClient
def initialize(api_key, redis_url = 'redis://localhost:6379/0')
@api_key = api_key
@base_url = 'https://demandapi.booking.com/3.1/cars/'
@redis = Redis.new(url: redis_url)
setup_connection
end
def setup_connection
@conn = Faraday.new(url: @base_url) do |faraday|
faraday.request :url_encoded
faraday.response :json, content_type: 'application/json'
faraday.adapter Faraday.default_adapter
faraday.headers['User-Agent'] = 'Ruby-RentalcarsTracker/1.0'
end
end
def get_car_details(car_id, use_cache = true)
cache_key = "car:#{car_id}"
if use_cache
cached_data = @redis.get(cache_key)
return JSON.parse(cached_data) if cached_data
end
response = @conn.get('/cars', { car_id: car_id, access_key: @api_key })
if response.status == 429
retry_after = response.headers['retry-after'] || 60
warn "Rate limit atteint. Retry dans #{retry_after}s"
sleep retry_after.to_i
return get_car_details(car_id, use_cache)
end
unless response.success?
raise "Erreur Rentalcars.com: #{response.body['message']}"
end
data = response.body
if use_cache && data['data'] && !data['data'].empty?
@redis.setex(cache_key, 300, data.to_json)
end
data
end
end
# Utilisation recommandée
client = RentalcarsClient.new(ENV['RENTALCARS_API_KEY'])
begin
car_data = client.get_car_details('CAR1234')
if car_data['data'].empty?
raise "Voiture CAR1234 non trouvée"
end
car = car_data['data'][0]
puts "Voiture #{car['car']['id']}: #{car['car']['status']}"
rescue => e
puts "Erreur lors du suivi: #{e.message}"
end
Bonnes Pratiques pour l'Utilisation de l'API
Pour tirer le meilleur parti de l'API CarTrawler, suivez ces bonnes pratiques :
- Utilisez des requêtes paginées pour éviter de surcharger votre application.
- Mettez en cache les réponses API pour améliorer les performances.
- Surveillez les limites de taux pour éviter les interruptions de service.
Conclusion
L'API CarTrawler est un outil indispensable pour les développeurs cherchant à intégrer des services de location de véhicules. Avec une documentation complète et un support technique dédié, vous pouvez rapidement et facilement ajouter cette fonctionnalité à vos applications.
Projets github utilisant l'api CarTrawler
Retrouvez ci-dessous une liste de projets github utilisant l'api CarTrawler. Vous pouvez cliquer sur les liens pour en savoir plus sur ces projets et voir comment ils utilisent l'api CarTrawler.
Connectez-vous pour ajouter un projet GitHub qui utilise cette API.
GitHubAucun projet GitHub utilisant cette API n'a encore été ajouté. Soyez le premier à en proposer un !
Commentaires sur l'api CarTrawler
Vous devez être connecté pour ajouter un commentaire.
API similaire à CarTrawler
Vous pouvez retrouver en cliquant sur le lien suivant toutes les APIs Voyage
Extrait des api similaires:
#48 - Voyage
Skyscanner API
Fournit des informations sur les vols, les hôtels et les locations de voitures.
#401 - Voyage
Booking.com
Accédez à l’offre d’hôtels, d’hébergements et de locations de Booking.com via leur API officielle pour enrichir vos projets de voyage.
#402 - Voyage
Expedia Rapid
Intégrez la recherche d’hôtels, de vols et de séjours avec l’Expedia Rapid API, parfaite pour enrichir vos plateformes de voyage et réservation.
#403 - Voyage
Amadeus Hotel Search
Utilisez l’Amadeus Hotel Search API pour accéder à des données d’hôtels fiables et enrichir vos plateformes de réservation et comparateurs de voyages.
#404 - Voyage
HotelsCombined
L’API HotelsCombined permet de comparer des offres d’hôtels dans le monde entier, idéale pour intégrer une solution de méta-recherche de voyages.
#405 - Voyage
Priceline Partner Network
L’API Priceline Partner Network permet d’intégrer des réservations d’hôtels, vols ou voitures dans vos plateformes de voyage, avec monétisation intégrée.
#406 - Voyage
Amadeus Flight
Amadeus Flight APIs vous permet d’intégrer la recherche, la tarification et la réservation de vols dans vos applications de voyage avec des données fiables.
#407 - Voyage
Kiwi.com
La Kiwi.com API permet d’intégrer une recherche multi-transports (vols, bus, trains) avec une logique de combinaison intelligente pour les voyages internationaux.
Aucun commentaire pour cet article.