Authentication overview

Metaphorsum provides a RESTful API designed for generating synthetic data, mocking APIs, and populating UI prototypes. Access to the Metaphorsum API is secured through API key authentication. This mechanism ensures that all requests originating from a client are authenticated and authorized to access the requested resources.

The Metaphorsum API expects the API key to be included in the Authorization header of every HTTP request. This approach aligns with common industry practices for securing RESTful services, providing a straightforward and manageable method for developers to integrate authentication into their applications. All communications with the Metaphorsum API are encrypted using Transport Layer Security (TLS) to protect data in transit, as detailed in the Metaphorsum security overview.

Metaphorsum's SDKs for Python and JavaScript abstract the underlying HTTP request details, simplifying the process of including the API key in your application. For direct HTTP integrations, developers are responsible for correctly formatting the request headers.

Supported authentication methods

Metaphorsum primarily supports API key authentication. This method is suitable for most use cases, including server-to-server communication, client-side applications where the key can be securely stored, and development environments.

API Key Authentication

API keys are unique identifiers that authenticate a user, developer, or calling program to an API. In Metaphorsum's context, an API key is a long, randomly generated string that grants access to your Metaphorsum account's resources. It acts as a secret token that must be protected.

When to use API keys:

  • Server-side applications: Ideal for backend services or scripts that make requests to Metaphorsum, where the API key can be stored securely in environment variables or secret management systems.
  • Development and testing: Convenient for rapid iteration and testing during the development phase.
  • Internal tools: For applications used within a controlled environment where key exposure risk is minimal.

When to consider alternatives (or additional security layers):

  • Public client-side applications: Directly embedding API keys in client-side code (e.g., in a browser or mobile app) is generally not recommended due to the risk of exposure. For such scenarios, consider using a proxy server or a backend-for-frontend (BFF) pattern to mediate requests and protect the key.
  • Granular permissions: While Metaphorsum API keys provide access to your account, they do not currently support fine-grained permissions per key. All keys associated with an account have the same level of access to that account's resources.

The following table summarizes the authentication method:

Method When to Use Security Level
API Key Server-side applications, internal tools, development environments Moderate to High (requires secure key management)

Getting your credentials

To obtain your Metaphorsum API key, you need to access your Metaphorsum account dashboard. The process involves creating an account and then generating a new API key.

  1. Sign Up or Log In: Navigate to the Metaphorsum login page and either create a new account or log in to an existing one.
  2. Access Dashboard: Once logged in, you will be directed to your Metaphorsum dashboard.
  3. Navigate to API Keys Section: Look for a section typically labeled "API Keys," "Settings," or "Developer Settings." This is usually found in the sidebar or a prominent navigation menu. Refer to the Metaphorsum API Key management guide for precise instructions.
  4. Generate New Key: Within the API Keys section, there will be an option to "Generate New API Key" or similar. Click this button.
  5. Name Your Key (Optional): Some systems allow you to name your API key for easier identification, especially if you plan to generate multiple keys for different applications.
  6. Copy Your Key: After generation, your new API key will be displayed. It is crucial to copy this key immediately and store it securely, as it may only be shown once for security reasons. If you lose it, you will likely need to revoke it and generate a new one.

Each API key is unique to your Metaphorsum account. Treat it as a password. If an API key is compromised, it should be revoked immediately from your Metaphorsum dashboard and a new one generated.

Authenticated request example

This section provides examples of how to include your Metaphorsum API key in requests using both curl for direct HTTP calls and the Python SDK.

Using curl (direct HTTP request)

When making direct HTTP requests, include your API key in the Authorization header with the prefix Bearer. Replace YOUR_METAPHORSUM_API_KEY with your actual key.

curl -X GET \
  'https://api.metaphorsum.com/v1/data/users' \
  -H 'Authorization: Bearer YOUR_METAPHORSUM_API_KEY' \
  -H 'Content-Type: application/json'

This curl command makes a GET request to the /v1/data/users endpoint, authenticating the request with the provided API key.

Using the Python SDK

The Metaphorsum Python SDK simplifies authentication by allowing you to configure your API key once, typically when initializing the client. The SDK then handles adding the key to subsequent requests.

import metaphorsum

# Configure the API key
metaphorsum.api_key = "YOUR_METAPHORSUM_API_KEY"

try:
    # Make an authenticated request
    users_data = metaphorsum.Data.list_users(limit=5)
    for user in users_data:
        print(f"User ID: {user['id']}, Name: {user['name']}")
except metaphorsum.exceptions.AuthenticationError as e:
    print(f"Authentication failed: {e}")
except metaphorsum.exceptions.APIError as e:
    print(f"API Error: {e}")

In this Python example, metaphorsum.api_key is set globally, and the Data.list_users() method automatically uses this key. For more detailed SDK usage, refer to the Metaphorsum Python SDK authentication guide.

Using the JavaScript SDK

Similar to Python, the JavaScript SDK allows you to set the API key during client initialization.

import Metaphorsum from 'metaphorsum';

const metaphorsumClient = new Metaphorsum({
  apiKey: 'YOUR_METAPHORSUM_API_KEY',
});

async function fetchUsers() {
  try {
    const users = await metaphorsumClient.data.listUsers({ limit: 5 });
    users.forEach(user => {
      console.log(`User ID: ${user.id}, Name: ${user.name}`);
    });
  } catch (error) {
    if (error.name === 'AuthenticationError') {
      console.error(`Authentication failed: ${error.message}`);
    } else {
      console.error(`API Error: ${error.message}`);
    }
  }
}

fetchUsers();

The JavaScript example demonstrates initializing the Metaphorsum client with the API key, which then handles authentication for subsequent API calls. Consult the Metaphorsum JavaScript SDK authentication guide for further details.

Security best practices

Securing your API keys is crucial to prevent unauthorized access to your Metaphorsum account and resources. Adhere to the following best practices:

  1. Treat API Keys as Passwords: API keys grant access to your account. Do not embed them directly in client-side code (e.g., web pages, mobile apps) where they can be easily extracted.
  2. Use Environment Variables: For server-side applications, store API keys in environment variables rather than hardcoding them in your source code. This keeps them out of version control and prevents accidental exposure. For example, in many operating systems, you can set METAPHORSUM_API_KEY="YOUR_KEY".
  3. Utilize Secret Management Services: For production environments, consider using dedicated secret management services like AWS Secrets Manager, Google Secret Manager, or Azure Key Vault. These services provide secure storage, rotation, and access control for sensitive credentials, as described in Google Cloud's Secret Manager overview.
  4. Restrict Access: Limit who has access to your API keys. Only individuals or systems that absolutely require access should have it. Implement appropriate access control policies.
  5. Regular Key Rotation: Periodically rotate your API keys. This practice minimizes the window of opportunity for a compromised key to be exploited. Metaphorsum allows you to revoke existing keys and generate new ones through your dashboard.
  6. Monitor Usage: Regularly review your API usage logs in the Metaphorsum dashboard for any unusual activity that might indicate a compromised key or unauthorized access.
  7. Secure Communication: Always ensure that all communication with the Metaphorsum API occurs over HTTPS to encrypt data in transit. Metaphorsum enforces HTTPS for all API endpoints.
  8. Implement Least Privilege: While Metaphorsum API keys currently grant full account access, if future versions offer more granular permissions, configure keys with the minimum necessary permissions for their intended task.
  9. Avoid Logging API Keys: Ensure that your application logs do not inadvertently capture or store API keys, even temporarily.
  10. Client-Side Proxies: If you must use Metaphorsum from a client-side application, route requests through your own backend proxy. The proxy can then securely add the API key before forwarding the request to Metaphorsum, preventing direct exposure of the key to the client.

By following these best practices, you can significantly reduce the risk of API key compromise and maintain the security of your Metaphorsum integrations.