Getting StartedGetting Started
Getting Started

Getting Started with the API

Start making API calls to the ACME Company API with step-by-step examples and practical use cases.

The ACME Company API provides a complete platform for managing your business data and operations. This guide walks you through making your first API calls and implementing common workflows.

Before You Start

Make sure you have:

  • API credentials - Get your API key from the dashboard
  • Base URL - All requests go to https://api.acme.com/v1
  • HTTP client - Use cURL, Postman, or your preferred programming language
  • Basic authentication - Review our authentication guide if needed

New to APIs? This guide assumes basic familiarity with REST APIs and HTTP methods. Check out our API basics tutorial if you're just getting started.

Your First API Call

Let's start by fetching the list of available pets:

curl -X GET "https://api.acme.com/v1/pets" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json"

Expected response:

{
  "pets": [
    {
      "id": 1,
      "name": "Buddy",
      "category": {
        "id": 1,
        "name": "Dogs"
      },
      "status": "available",
      "age": 3,
      "breed": "Golden Retriever"
    },
    {
      "id": 2,
      "name": "Whiskers", 
      "category": {
        "id": 2,
        "name": "Cats"
      },
      "status": "available",
      "age": 2,
      "breed": "Persian"
    }
  ],
  "pagination": {
    "limit": 20,
    "offset": 0,
    "total": 2,
    "hasMore": false
  }
}

Success! If you received a response with pet data, your authentication is working correctly and you're ready to explore more endpoints.

Common API Workflows

1. Creating a New Pet

Add a pet to the store with all required information:

Endpoint: POST /pets

Required fields:

  • name - Pet's name
  • categoryId - Category identifier
  • status - Pet status (available, pending, or sold)
const newPet = {
  name: "Max",
  categoryId: 1, // Dogs category
  status: "available",
  age: 2,
  breed: "Labrador",
  description: "Friendly and energetic dog, great with kids"
};

const response = await fetch('https://api.acme.com/v1/pets', {
  method: 'POST',
  headers: {
    'X-API-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(newPet)
});

const createdPet = await response.json();
console.log('Created pet with ID:', createdPet.id);

Successful response (Status 201):

{
  "id": 123,
  "name": "Max",
  "category": {
    "id": 1,
    "name": "Dogs"
  },
  "status": "available",
  "age": 2,
  "breed": "Labrador",
  "description": "Friendly and energetic dog, great with kids",
  "photoUrls": [],
  "tags": [],
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-15T10:30:00Z"
}

2. Searching and Filtering Pets

Find pets based on specific criteria:

Available query parameters:

  • status - Filter by availability (available, pending, sold)
  • category - Filter by category name
  • limit - Number of results (default: 20, max: 100)
  • offset - Skip results for pagination
// Find all available dogs
const response = await fetch(
  'https://api.acme.com/v1/pets?status=available&category=Dogs&limit=10',
  {
    headers: {
      'X-API-Key': 'YOUR_API_KEY',
      'Content-Type': 'application/json'
    }
  }
);

const availableDogs = await response.json();
console.log(`Found ${availableDogs.pets.length} available dogs`);

3. Updating Pet Information

Modify existing pet details:

Endpoint: PUT /pets/{petId}

Common status updates:

  • availablepending (adoption in progress)
  • pendingsold (adoption completed)
  • soldavailable (returned to store)
async function updatePetStatus(petId, newStatus) {
  const updateData = {
    status: newStatus
  };

  const response = await fetch(`https://api.acme.com/v1/pets/${petId}`, {
    method: 'PUT',
    headers: {
      'X-API-Key': 'YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updateData)
  });

  if (response.ok) {
    const updatedPet = await response.json();
    console.log(`Pet ${updatedPet.name} status updated to: ${updatedPet.status}`);
    return updatedPet;
  } else {
    throw new Error(`Failed to update pet: ${response.status}`);
  }
}

// Usage examples
await updatePetStatus(123, 'pending'); // Mark as adoption in progress
await updatePetStatus(456, 'sold');    // Mark as successfully adopted

4. Managing Categories

Work with pet categories for better organization:

Endpoint: GET /categories

const response = await fetch('https://api.acme.com/v1/categories', {
  headers: {
    'X-API-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
});

const { categories } = await response.json();

categories.forEach(category => {
  console.log(`${category.id}: ${category.name} - ${category.description}`);
});

Expected response:

{
  "categories": [
    {
      "id": 1,
      "name": "Dogs",
      "description": "All types of dogs"
    },
    {
      "id": 2, 
      "name": "Cats",
      "description": "All types of cats"
    },
    {
      "id": 3,
      "name": "Birds",
      "description": "All types of birds"
    }
  ]
}

Image Upload and Management

Uploading Pet Photos

Endpoint: POST /pets/{petId}/upload-image

async function uploadPetImage(petId, imageFile, description) {
  const formData = new FormData();
  formData.append('image', imageFile);
  formData.append('description', description);

  const response = await fetch(`https://api.acme.com/v1/pets/${petId}/upload-image`, {
    method: 'POST',
    headers: {
      'X-API-Key': 'YOUR_API_KEY'
      // Don't set Content-Type for FormData - browser will set it automatically
    },
    body: formData
  });

  const result = await response.json();
  console.log('Image uploaded:', result.imageUrl);
  return result;
}

// Usage with file input
const fileInput = document.querySelector('#pet-photo');
const file = fileInput.files[0];

if (file) {
  await uploadPetImage(123, file, 'Main profile photo');
}

Response:

{
  "message": "Image uploaded successfully",
  "imageUrl": "https://images.acme.com/pets/123/main.jpg"
}

Image requirements: JPG, PNG, or GIF formats up to 5MB. Images are automatically resized to optimize loading times while maintaining quality.

Error Handling Best Practices

Robust Error Handling Pattern

class PetStoreAPI {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.acme.com/v1';
  }

  async request(endpoint, options = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    
    const response = await fetch(url, {
      ...options,
      headers: {
        'X-API-Key': this.apiKey,
        'Content-Type': 'application/json',
        ...options.headers
      }
    });

    // Handle different error types
    if (!response.ok) {
      await this.handleError(response);
    }

    return response.json();
  }

  async handleError(response) {
    const errorData = await response.json();
    
    switch (response.status) {
      case 400:
        throw new Error(`Bad Request: ${errorData.message}`);
      case 401:
        throw new Error('Unauthorized: Check your API key');
      case 404:
        throw new Error(`Not Found: ${errorData.message}`);
      case 429:
        const retryAfter = response.headers.get('Retry-After') || 60;
        throw new Error(`Rate limited. Try again in ${retryAfter} seconds`);
      case 500:
        throw new Error('Server error. Please try again later');
      default:
        throw new Error(`API Error (${response.status}): ${errorData.message}`);
    }
  }

  // Convenience methods
  async getPets(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.request(`/pets${query ? `?${query}` : ''}`);
  }

  async getPet(id) {
    return this.request(`/pets/${id}`);
  }

  async createPet(petData) {
    return this.request('/pets', {
      method: 'POST',
      body: JSON.stringify(petData)
    });
  }

  async updatePet(id, updates) {
    return this.request(`/pets/${id}`, {
      method: 'PUT',
      body: JSON.stringify(updates)
    });
  }
}

// Usage
const api = new PetStoreAPI('YOUR_API_KEY');

try {
  const pets = await api.getPets({ status: 'available', limit: 10 });
  console.log('Available pets:', pets);
} catch (error) {
  console.error('Error fetching pets:', error.message);
}

Rate Limits and Optimization

Understanding Rate Limits

The ACME Company API enforces the following rate limits:

AuthenticationRequests per HourBurst Limit
API Key1,000100 per minute
JWT Token5,000300 per minute
Unauthenticated10020 per minute

Rate limit headers in responses:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642694400

Optimization Strategies

class OptimizedPetStoreAPI extends PetStoreAPI {
  constructor(apiKey) {
    super(apiKey);
    this.cache = new Map();
    this.cacheTimeout = 5 * 60 * 1000; // 5 minutes
  }

  // Cache frequently accessed data
  async getCachedPet(id) {
    const cacheKey = `pet_${id}`;
    const cached = this.cache.get(cacheKey);
    
    if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
      return cached.data;
    }

    const pet = await this.getPet(id);
    this.cache.set(cacheKey, {
      data: pet,
      timestamp: Date.now()
    });

    return pet;
  }

  // Batch multiple pet requests
  async getMultiplePets(ids) {
    const promises = ids.map(id => this.getCachedPet(id));
    return Promise.all(promises);
  }

  // Intelligent pagination
  async getAllPetsInCategory(categoryName, batchSize = 50) {
    const allPets = [];
    let offset = 0;
    let hasMore = true;

    while (hasMore) {
      const result = await this.getPets({
        category: categoryName,
        limit: batchSize,
        offset: offset
      });

      allPets.push(...result.pets);
      hasMore = result.pagination.hasMore;
      offset += batchSize;

      // Add small delay to be respectful of rate limits
      if (hasMore) {
        await new Promise(resolve => setTimeout(resolve, 100));
      }
    }

    return allPets;
  }
}

Next Steps

Great job! You've learned the fundamentals of the ACME Company API. You can now create, read, update, and manage pets and categories.

Explore More Features

Common Next Steps

  1. Build a pet listing application with search and filtering
  2. Implement user authentication for customer accounts
  3. Add real-time updates with webhooks
  4. Create an admin dashboard for pet management
  5. Integrate with payment systems for adoption fees

Get Help