Getting StartedAuthentication
Getting Started

Authentication

Learn how to authenticate with the ACME Company API using API keys and bearer tokens.

The ACME Company API uses multiple authentication methods to ensure secure access to your data. Choose the method that best fits your use case and security requirements.

Authentication Methods

API Key Authentication

The simplest way to authenticate with the ACME Company API is using an API key passed in the request header.

Header format:

X-API-Key: your_api_key_here

Example request:

curl -X GET "https://api.acme.com/v1/pets" \
  -H "X-API-Key: pk_live_51H9X2LKjI8mZ2gH8vK3nR7..."
# Using cURL with API key
curl -X GET "https://api.acme.com/v1/pets" \
  -H "X-API-Key: pk_live_51H9X2LKjI8mZ2gH8vK3nR7..." \
  -H "Content-Type: application/json"

Bearer Token Authentication (JWT)

For more secure applications, use JWT bearer tokens obtained through the authentication endpoint.

Header format:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Authentication flow:

  1. Obtain a token by calling the /auth/login endpoint
  2. Include the token in the Authorization header for subsequent requests
  3. Refresh the token before it expires (tokens are valid for 1 hour)

Endpoint: POST /auth/login

Request body:

{
  "username": "your_username",
  "password": "your_password"
}

Example request:

curl -X POST "https://api.acme.com/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john.doe",
    "password": "secure_password_123"
  }'

Successful response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": 123,
    "username": "john.doe",
    "email": "john.doe@acme.com"
  },
  "expiresIn": 3600
}

Getting Your API Credentials

Creating an API Key

API keys are perfect for server-side applications and testing. They don't expire but should be kept secure.

  1. Log in to your Pet Store dashboard at dashboard.acme.com
  2. Navigate to Settings → API Keys
  3. Click "Generate New API Key"
  4. Give your key a descriptive name (e.g., "Production Server", "Development Testing")
  5. Copy the key immediately - it won't be shown again
  6. Store the key securely in your environment variables

API key format:

  • Live keys: pk_live_... (for production use)
  • Test keys: pk_test_... (for development and testing)

Security warning: Never commit API keys to version control or expose them in client-side code. Store them as environment variables or in secure key management systems.

Creating User Accounts

For JWT authentication, you'll need a user account:

  1. Register at the Pet Store platform or have an admin create your account
  2. Verify your email address if required
  3. Use your username and password with the /auth/login endpoint
  4. Store the returned JWT token securely in your application

Security Best Practices

Protecting Your Credentials

Store credentials in environment variables, not in your code:

Development (.env file):

# .env file (never commit this!)
PETSTORE_API_KEY=pk_test_51H9X2LKjI8mZ2gH8vK3nR7...
PETSTORE_USERNAME=john.doe
PETSTORE_PASSWORD=secure_password_123
PETSTORE_BASE_URL=https://api.acme.com/v1

Usage in code:

// Load from environment variables
const apiKey = process.env.PETSTORE_API_KEY;
const username = process.env.PETSTORE_USERNAME;
const password = process.env.PETSTORE_PASSWORD;

// Never do this:
// const apiKey = "pk_live_51H9X2LKjI8mZ2gH8vK3nR7..."; ❌

Production deployment:

  • Use your hosting platform's environment variable settings
  • Consider using secret management services (AWS Secrets Manager, Azure Key Vault, etc.)
  • Rotate credentials regularly

Error Responses

Common Authentication Errors

Status CodeError CodeDescriptionSolution
401INVALID_API_KEYAPI key is invalid or malformedCheck your API key format and regenerate if needed
401EXPIRED_TOKENJWT token has expiredRe-authenticate to get a fresh token
401INVALID_CREDENTIALSUsername/password combination is incorrectVerify credentials and account status
403INSUFFICIENT_PERMISSIONSAccount lacks required permissionsContact support to upgrade your account
429RATE_LIMIT_EXCEEDEDToo many requests in time windowWait for rate limit reset or upgrade plan

Example error response:

{
  "code": "EXPIRED_TOKEN",
  "message": "The provided JWT token has expired",
  "details": {
    "expired_at": "2024-01-15T14:30:00Z",
    "current_time": "2024-01-15T15:45:00Z"
  }
}

Handling Errors Gracefully

async function handleApiError(response) {
  const errorData = await response.json();
  
  switch (errorData.code) {
    case 'EXPIRED_TOKEN':
      // Attempt to refresh token
      console.log('Token expired, refreshing...');
      return await refreshToken();
      
    case 'RATE_LIMIT_EXCEEDED':
      // Wait and retry
      const retryAfter = response.headers.get('Retry-After') || 60;
      console.log(`Rate limited, waiting ${retryAfter}s`);
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      return 'retry';
      
    case 'INVALID_API_KEY':
      // This requires manual intervention
      throw new Error('API key is invalid. Please check your configuration.');
      
    default:
      throw new Error(`API Error: ${errorData.message}`);
  }
}

Testing Authentication

Quick Test Commands

Verify your authentication is working:

# Test API key authentication
curl -X GET "https://api.acme.com/v1/pets" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -w "Status: %{http_code}
"

# Expected: Status 200 with pet data

Authentication setup complete! You're now ready to start making authenticated requests to the ACME Company API. Check out our Getting Started guide for your first API calls.


What's next?