Skip to content

APOGEOAPI/apogeoapi-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

apogeoapi — JavaScript/TypeScript SDK

Official TypeScript SDK for ApogeoAPI — professional geographic data API with comprehensive country, state, and city information, IP geolocation, and exchange rates.

npm version License: MIT

Features

  • Full TypeScript Support - Complete type definitions with autocomplete
  • Auto-Retry Logic - Automatic retry with exponential backoff
  • Error Handling - Typed error responses
  • Rate Limit Handling - Respects retry-after headers
  • Multiple Auth Methods - API Key or JWT token
  • Comprehensive Coverage - All API endpoints covered
  • Zero Config - Works out of the box with sensible defaults

Installation

npm install apogeoapi

# or with yarn
yarn add apogeoapi

# or with pnpm
pnpm add apogeoapi

Quick Start

import { ApogeoAPI } from 'apogeoapi';

// Initialize with API key (recommended)
const client = new ApogeoAPI({
  apiKey: 'geoapi_live_xxxxx'
});

// Get all countries
const countries = await client.geo.getCountries();
console.log(`Total countries: ${countries.length}`);

// Search for cities
const cities = await client.geo.searchCities('New York', 10);
console.log(cities);

// Get usage statistics
const dashboard = await client.account.getDashboard();
console.log(`API calls this month: ${dashboard.usage.requestsThisMonth}`);

Table of Contents


Authentication

API Key (Recommended for Client-Side)

const client = new ApogeoAPI({
  apiKey: 'geoapi_live_xxxxx'
});

JWT Token (After Login)

const client = new ApogeoAPI({
  token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
});

// Or set token after initialization
client.setToken('new_token_here');

Register & Login

// Register new user
const { user, access_token, refresh_token } = await client.auth.register({
  email: 'user@example.com',
  password: 'securePassword123',
  username: 'johndoe'
});

// Login
const tokens = await client.auth.login({
  email: 'user@example.com',
  password: 'securePassword123'
});

// Token is automatically set after login
console.log('Logged in as:', tokens.user.username);

// Refresh token
const newTokens = await client.auth.refreshToken({
  refresh_token: tokens.refresh_token
});

Geography API

Countries

// Get all countries
const countries = await client.geo.getCountries();

// Get country by ISO code
const usa = await client.geo.getCountryByIso('US');
console.log(usa.name); // "United States"
console.log(usa.capital); // "Washington"
console.log(usa.currency); // "USD"

// Search countries
const matching = await client.geo.searchCountries('united', 5);

States/Provinces

// Get all states of a country
const usStates = await client.geo.getStates('US');
console.log(`US has ${usStates.length} states`);

// Get specific state
const california = await client.geo.getStateById(1234);
console.log(california.name); // "California"

// Search states
const texasMatch = await client.geo.searchStates('texas', 1);

Cities

// Get cities of a state
const californiaCities = await client.geo.getCities(1234, 100, 0);

// Get specific city
const city = await client.geo.getCityById(5678);
console.log(`${city.name}, ${city.state.name}`);

// Search cities
const newYorkCities = await client.geo.searchCities('New York', 10);

Universal Search

// Search across all types
const results = await client.geo.search({
  query: 'san',
  limit: 20,
  offset: 0,
  type: 'city' // optional: 'country' | 'state' | 'city'
});

console.log(`Found ${results.total} results`);

Account Management

Dashboard

// Get complete dashboard
const dashboard = await client.account.getDashboard();

console.log('User:', dashboard.user.username);
console.log('Tier:', dashboard.subscription.tier);
console.log('Usage:', dashboard.usage.requestsThisMonth, '/', dashboard.usage.monthlyQuota);
console.log('API Keys:', dashboard.apiKeys.active, '/', dashboard.apiKeys.max);

Profile

// Update profile
await client.account.updateProfile({
  username: 'new_username',
  email: 'newemail@example.com'
});

// Change password
await client.account.changePassword({
  currentPassword: 'oldpass123',
  newPassword: 'newpass456'
});

Usage Statistics

// Get usage for date range
const stats = await client.account.getUsage({
  startDate: new Date('2024-01-01'),
  endDate: new Date('2024-01-31'),
  groupBy: 'day' // or 'month'
});

stats.forEach(stat => {
  console.log(`${stat.date}: ${stat.requests} requests`);
});

API Keys Management

List & Create

// List all API keys
const keys = await client.apiKeys.list();

// Create new API key
const newKey = await client.apiKeys.create({
  name: 'Production Server',
  expiresAt: new Date('2025-12-31')
});

console.log('Save this key:', newKey.key);
// Key is only shown once!

Update & Delete

// Rename key
await client.apiKeys.update(keyId, {
  name: 'Production Server v2'
});

// Revoke key (deactivate)
await client.apiKeys.revoke(keyId);

// Reactivate key
await client.apiKeys.activate(keyId);

// Delete permanently
await client.apiKeys.delete(keyId);

Billing & Subscriptions

Upgrade Plan

// Create checkout session
const checkout = await client.billing.createCheckoutSession(
  'professional', // tier
  'https://myapp.com/success', // success URL
  'https://myapp.com/cancel' // cancel URL
);

// Redirect user to payment page
window.location.href = checkout.url;

Manage Subscription

// Access billing portal
const portal = await client.billing.createPortalSession(
  'https://myapp.com/account' // return URL
);

// Redirect user to billing portal
window.location.href = portal.url;

Invoices

// Get all invoices
const invoices = await client.billing.getInvoices(10);

invoices.forEach(invoice => {
  console.log(`${invoice.created}: $${invoice.amount/100} - ${invoice.status}`);
  console.log(`PDF: ${invoice.invoice_pdf}`);
});

// Get specific invoice
const invoice = await client.billing.getInvoice('in_xxxxx');

Cancel Subscription

// Cancel at period end
await client.billing.cancelSubscription();
// User keeps access until period ends

// Reactivate before period ends
await client.billing.reactivateSubscription();

Webhooks

Create Webhook

// Create webhook
const webhook = await client.webhooks.create({
  url: 'https://myapp.com/webhooks/apogeoapi',
  events: [
    'usage.quota_warning',
    'usage.quota_exceeded',
    'subscription.updated'
  ]
});

console.log('Webhook ID:', webhook.id);
console.log('Secret:', webhook.secret); // Use to validate payloads

Manage Webhooks

// List all webhooks
const webhooks = await client.webhooks.list();

// Update webhook
await client.webhooks.update(webhookId, {
  url: 'https://myapp.com/new-webhook-url',
  events: ['subscription.created', 'subscription.canceled']
});

// Test webhook
const result = await client.webhooks.test(webhookId);
console.log('Test success:', result.success);

// Deactivate
await client.webhooks.deactivate(webhookId);

// Delete
await client.webhooks.delete(webhookId);

Delivery Logs

// Get webhook delivery logs
const logs = await client.webhooks.getLogs(webhookId, 50);

logs.forEach(log => {
  console.log(`${log.createdAt}: ${log.event} - ${log.success ? 'OK' : 'FAIL'}`);
  if (!log.success) {
    console.log(`  Status: ${log.statusCode}`);
  }
});

Error Handling

import { ApogeoAPI, ApogeoAPIError } from 'apogeoapi';

const client = new ApogeoAPI({ apiKey: 'xxx' });

try {
  const country = await client.geo.getCountryByIso('INVALID');
} catch (error) {
  if (error instanceof ApogeoAPIError) {
    console.error('Status:', error.statusCode);
    console.error('Message:', error.message);
    console.error('Response:', error.response);

    // Handle specific errors
    if (error.statusCode === 404) {
      console.log('Country not found');
    } else if (error.statusCode === 429) {
      console.log('Rate limit exceeded, retry after:', error.response?.retryAfter);
    } else if (error.statusCode === 403) {
      console.log('Quota exceeded or invalid API key');
    }
  } else {
    console.error('Unexpected error:', error);
  }
}

Advanced Configuration

Custom Configuration

const client = new ApogeoAPI({
  apiKey: 'geoapi_live_xxxxx',
  baseURL: 'https://api.apogeoapi.com/v1',
  timeout: 30000, // 30 seconds
  retries: 3, // retry failed requests 3 times
  debug: true // enable debug logging
});

Debug Mode

const client = new ApogeoAPI({
  apiKey: 'xxx',
  debug: true
});

// Logs all requests and retries
// [SDK] GET /geo/countries
// [SDK] Response 200 from /geo/countries

Using Different Environments

// Development
const devClient = new ApogeoAPI({
  apiKey: process.env.DEV_API_KEY,
  baseURL: 'http://localhost:3000/v1'
});

// Production
const prodClient = new ApogeoAPI({
  apiKey: process.env.PROD_API_KEY,
  baseURL: 'https://api.apogeoapi.com/v1'
});

Examples

Complete Application Example

import { ApogeoAPI } from 'apogeoapi';

const client = new ApogeoAPI({
  apiKey: process.env.GEO_API_KEY!
});

async function main() {
  // 1. Get dashboard
  const dashboard = await client.account.getDashboard();
  console.log(`Welcome ${dashboard.user.username}!`);
  console.log(`You're on the ${dashboard.subscription.tier} plan`);
  console.log(`Usage: ${dashboard.usage.usagePercentage}%`);

  // 2. Query geography data
  const countries = await client.geo.getCountries();
  console.log(`\nTotal countries: ${countries.length}`);

  // 3. Search for specific location
  const cities = await client.geo.searchCities('Paris', 5);
  console.log(`\nCities named Paris:`);
  cities.forEach(city => {
    console.log(`- ${city.name}, ${city.state?.name}, ${city.country?.name}`);
  });

  // 4. Check usage
  const usage = await client.account.getUsage({
    startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
    endDate: new Date(),
    groupBy: 'day'
  });
  console.log(`\nLast 30 days usage:`, usage.length, 'days');
}

main().catch(console.error);

TypeScript Support

Full TypeScript support with complete type definitions:

import { ApogeoAPI, Country, City, Tier, WebhookEvent } from 'apogeoapi';

const client = new ApogeoAPI({ apiKey: 'xxx' });

// All responses are fully typed
const country: Country = await client.geo.getCountryByIso('US');
const cities: City[] = await client.geo.searchCities('London', 10);

// Enums are typed
const tier: Tier = 'professional';
const events: WebhookEvent[] = ['usage.quota_warning', 'subscription.updated'];

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

MIT © ApogeoAPI

Links


Made with care by the ApogeoAPI Team

About

Official JavaScript/TypeScript SDK for ApogeoAPI — IP geolocation, countries, cities and exchange rates

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors