Your First API Integration

Introduction

This guide will walk you through integrating your first API with API Aggregator. We'll use a simple REST API example to demonstrate the core concepts.

Prerequisites

  • API Aggregator installed (see installation guide)
  • Basic understanding of REST APIs
  • An API endpoint to integrate

Step-by-Step Integration

1. Configure Your API

Add your API configuration to api-config.json:

{
  "apis": {
    "weather-api": {
      "baseUrl": "https://api.weatherservice.com/v1",
      "auth": {
        "type": "apiKey",
        "key": "x-api-key",
        "value": "YOUR_API_KEY"
      },
      "headers": {
        "Accept": "application/json"
      }
    }
  }
}

2. Create Your First Integration

Create a new file weather.ts:

import { APIAggregator } from '@api-aggregator/core';

export class WeatherService {
  private api: APIAggregator;

  constructor() {
    this.api = new APIAggregator();
  }

  async getWeather(city: string) {
    return await this.api.call('weather-api', '/weather', {
      params: { city }
    });
  }
}

3. Implement Error Handling

Add error handling to your integration:

try {
  const weather = await weatherService.getWeather('London');
  console.log('Weather:', weather);
} catch (error) {
  if (error.status === 401) {
    console.error('Authentication failed');
  } else if (error.status === 404) {
    console.error('City not found');
  } else {
    console.error('An error occurred:', error.message);
  }
}

4. Add Response Transformation

Transform API responses to match your application's needs:

export interface WeatherData {
  temperature: number;
  condition: string;
  humidity: number;
}

async getWeather(city: string): Promise<WeatherData> {
  const response = await this.api.call('weather-api', '/weather', {
    params: { city },
    transform: (data) => ({
      temperature: data.temp,
      condition: data.weather_condition,
      humidity: data.humidity_level
    })
  });
  return response;
}

Testing Your Integration

Create a test file to verify your integration:

import { WeatherService } from './weather';

describe('WeatherService', () => {
  it('should fetch weather data', async () => {
    const service = new WeatherService();
    const weather = await service.getWeather('London');

    expect(weather).toHaveProperty('temperature');
    expect(weather).toHaveProperty('condition');
    expect(weather).toHaveProperty('humidity');
  });
});

Best Practices

  • Always handle API errors appropriately
  • Use TypeScript interfaces for type safety
  • Implement proper error handling
  • Add request/response logging for debugging
  • Use environment variables for sensitive data

Next Steps

Now that you've created your first integration, you can:

  • Add more API endpoints
  • Implement caching strategies
  • Add rate limiting
  • Set up monitoring and logging
  • Explore advanced features