Getting started overview

This guide provides a focused approach to initiating development with the Metaphorsum API. It details the steps required to create an account, secure API credentials, and execute a foundational request. The objective is to enable developers to generate synthetic data for various purposes, such as populating prototypes or augmenting testing data sets.

Before proceeding, ensure you have access to a web browser, an active email account, and a development environment capable of executing Python or JavaScript code, as these are the primary Metaphorsum SDK languages. Familiarity with HTTP methods and JSON data structures is also beneficial for interacting with RESTful APIs.

Quick Reference Steps

The following table outlines the key steps to get Metaphorsum operational:

Step Action Where to perform
1 Create a Metaphorsum account Metaphorsum Signup Page
2 Obtain API Key Metaphorsum Dashboard > API Keys
3 Install SDK (optional, recommended) Local development environment
4 Write and execute first request Local development environment
5 Verify data generation Console output or application integration

Create an account and get keys

Access to the Metaphorsum API requires an active account and API credentials. These credentials authenticate your requests and link them to your usage limits.

Account Creation

  1. Navigate to the Metaphorsum signup page.
  2. Provide a valid email address and create a password.
  3. Complete any required email verification process.
  4. Upon successful signup, you will be directed to the Metaphorsum dashboard.

Metaphorsum offers a Starter free tier, which includes up to 500 API calls per month, sufficient for initial testing and exploration.

API Key Generation

API keys are unique identifiers used to authenticate your application with the Metaphorsum API. Treat your API key as sensitive information, similar to a password. Do not expose it in client-side code or public repositories.

  1. From your Metaphorsum dashboard, locate the "API Keys" section. The exact navigation may vary slightly but typically appears under "Settings" or "Developer." Refer to the Metaphorsum authentication documentation for precise location details.
  2. Click the "Generate New Key" or similar button.
  3. Assign a descriptive name to your API key (e.g., "My First Project Key").
  4. Copy the generated API key immediately. It may not be displayed again after you leave the page.

Store your API key securely. Best practices involve using environment variables or a secrets management service rather than hardcoding it directly into your application code. For example, in a local development environment, you might set it as an environment variable: METAPHORSUM_API_KEY=sk_********************.

Your first request

Once you have your API key, you can make your first request to generate synthetic data. Metaphorsum supports direct HTTP requests and provides SDKs for Python and JavaScript to simplify integration.

API Endpoint Overview

The primary Metaphorsum API endpoint for data generation is typically /v1/generate. This endpoint accepts a JSON payload defining the schema of the data you wish to generate. For detailed information on available fields and parameters, consult the Metaphorsum API reference.

Using the Python SDK

First, install the Python SDK:

pip install metaphorsum

Then, create a Python script (e.g., generate_data.py) with the following content. Replace YOUR_API_KEY with your actual Metaphorsum API key, ideally retrieved from an environment variable.

import os
from metaphorsum import MetaphorsumClient

# It's recommended to store your API key in an environment variable
api_key = os.getenv("METAPHORSUM_API_KEY", "YOUR_API_KEY")
client = MetaphorsumClient(api_key=api_key)

try:
    # Define the schema for the data you want to generate
    schema = {
        "name": "person.full_name",
        "email": "internet.email",
        "age": "number.between(18, 65)"
    }

    # Generate 3 records based on the schema
    generated_data = client.generate(schema=schema, count=3)

    print("Generated Data:")
    for record in generated_data:
        print(record)
except Exception as e:
    print(f"An error occurred: {e}")

Execute the script:

python generate_data.py

This script will connect to the Metaphorsum API, request three records matching the defined schema (full name, email, and age between 18 and 65), and print the resulting JSON objects to your console.

Using the JavaScript SDK

First, install the JavaScript SDK:

npm install metaphorsum
# or
yarn add metaphorsum

Then, create a JavaScript file (e.g., generateData.js) with the following content. Replace YOUR_API_KEY with your actual Metaphorsum API key, ideally retrieved from an environment variable.

const { MetaphorsumClient } = require('metaphorsum');

// It's recommended to store your API key in an environment variable
const apiKey = process.env.METAPHORSUM_API_KEY || 'YOUR_API_KEY';
const client = new MetaphorsumClient(apiKey);

async function generateData() {
  try {
    // Define the schema for the data you want to generate
    const schema = {
      name: 'person.full_name',
      email: 'internet.email',
      city: 'address.city',
    };

    // Generate 2 records based on the schema
    const generatedData = await client.generate({ schema, count: 2 });

    console.log('Generated Data:');
    generatedData.forEach(record => console.log(record));
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

generateData();

Execute the script:

node generateData.js

This script will request two records, each with a full name, email, and city, and output the generated JSON to the console.

Common next steps

After successfully making your first request, consider these common next steps to further integrate Metaphorsum into your development workflow:

  • Explore Advanced Schemas: Experiment with more complex data types, nested objects, and conditional logic within your schemas. The Metaphorsum schema definition guide offers extensive examples.
  • Integrate with Testing Frameworks: Use Metaphorsum to populate databases or mock API responses for unit, integration, and end-to-end tests. This provides realistic data without relying on production systems.
  • Automate Data Generation: Incorporate Metaphorsum API calls into CI/CD pipelines to ensure fresh, relevant test data is always available for automated tests.
  • Utilize the Web UI: For interactive schema building and data preview, explore the Metaphorsum Web UI. It can help visualize how different schema definitions translate into generated data.
  • Monitor Usage: Keep track of your API call usage through the Metaphorsum dashboard to manage your pricing plan effectively.
  • Review Security Best Practices: Ensure your API key is handled securely in production environments, potentially utilizing practices such as those outlined by Google's API key security best practices.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some steps to diagnose and resolve typical problems:

  • Check API Key: Double-check that your API key is correct and has not expired. Ensure there are no leading or trailing spaces. Verify it is included correctly in your request headers or SDK initialization.
  • Environment Variable Access: If using environment variables, confirm that they are properly set and accessible within your script's execution environment. For example, restart your terminal or IDE if you've just set a new variable.
  • Schema Validation Errors: The Metaphorsum API will return validation errors if your schema definition is malformed or uses unsupported data types. Consult the Metaphorsum API error codes and schema documentation to correct the payload.
  • Network Connectivity: Ensure your development machine has an active internet connection and is not blocked by a firewall or proxy from accessing api.metaphorsum.com.
  • Rate Limiting: If you exceed the allowed number of requests for your plan (especially on the free tier), you might receive rate limit errors. Check your dashboard for current usage and the Metaphorsum rate limiting policy.
  • SDK Version: Ensure you are using a recent and compatible version of the Python or JavaScript SDK. Outdated SDKs might lack support for newer API features or have known bugs.
  • Detailed Error Messages: Pay close attention to the error messages returned by the API or the SDK. They often contain specific information that can guide your troubleshooting.
  • Consult Documentation: The official Metaphorsum documentation is the authoritative source for troubleshooting and detailed API usage.
  • Contact Support: If you continue to experience issues, gather relevant details (request payload, error messages, API key scope) and contact Metaphorsum support.