API Documentation

Complete guide to using PromptHub API keys to access your prompts programmatically.

Overview

PromptHub API allows you to programmatically access your prompts using API keys. Retrieve prompts using the readable username/repository/prompt name format, with optional version parameters for accessing specific versions. API keys provide access to public repositories or private repositories they're scoped to.

Readable URLs

Access prompts using human-readable paths with username, repository name, and prompt name. Optionally specify version numbers for specific versions.

Secure Authentication

API keys use Bearer token authentication for secure access and are shown only once during creation.

Authentication

All API requests must include your API key in the Authorization header using Bearer token format. API keys provide access to all prompts in the project.

Header Format:

Authorization: Bearer pm-your-api-key-here

API Endpoints

GEThttps://prompthub.dev/api/v1/repositories/{username}/{repoName}/prompts/{promptName}

Retrieve a prompt by username, repository name, and prompt name. This endpoint provides access to prompts from public repositories (with any valid API key) or private repositories (with API keys scoped to that repository).

Parameters

username (path parameter) - The repository owner's username
repoName (path parameter) - The repository name
promptName (path parameter) - The prompt identifier
version (query parameter, optional) - Specific version number
Example: ?version=3

Example Request

curl -X GET \\
-H "Authorization: Bearer pm-your-api-key-here" \\
"https://prompthub.dev/api/v1/repositories/john/my-project/prompts/welcome_message"

Example Response

{
  "prompt": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "prompt_id": "welcome_message",
    "content": "Welcome to our platform! We're excited to have you here...",
    "context": {
      "tone": "friendly",
      "audience": "new_users"
    },
    "version": 1,
    "created_at": "2024-01-15T10:30:00Z",
    "updated_at": "2024-01-15T10:30:00Z",
    "change_description": "Initial version",
    "repository": {
      "id": "repo-456",
      "name": "my-project",
      "description": "My awesome project",
      "visibility": "public"
    },
    "created_by": {
      "id": "user-789",
      "email": "john@example.com",
      "full_name": "John Doe"
    },
    "tags": [
      {
        "id": "tag-123",
        "name": "production"
      }
    ],
    "model_configuration": null
  }
}

Error Responses

401 Unauthorized

Invalid or missing API key

{ "error": "Invalid API key" }

400 Bad Request

Invalid parameter format or values

{ "error": "Invalid username format. Only letters, numbers, underscores, and hyphens are allowed." }

403 Forbidden

Access denied to private repository

{ "error": "Prompt not found or access denied" }

404 Not Found

Repository, prompt not found, or tag/version does not exist

{ "error": "Prompt not found or access denied" }

500 Internal Server Error

Server error

{ "error": "Internal server error" }

Code Examples

JavaScriptNode.js / Browser

const apiKey = 'pm-your-api-key-here';

async function getPrompt(username, repoName, promptName, version = null) {
  try {
    let url = `https://prompthub.dev/api/v1/repositories/${username}/${repoName}/prompts/${promptName}`;
    if (version) {
      url += `?version=${version}`;
    }
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data.prompt;
  } catch (error) {
    console.error('Error fetching prompt:', error);
    throw error;
  }
}

// Usage examples
// Get latest version of prompt
getPrompt('john', 'my-project', 'welcome_message')
  .then(prompt => console.log(prompt.content))
  .catch(error => console.error(error));

// Get specific version
getPrompt('john', 'my-project', 'welcome_message', 3)
  .then(prompt => console.log(`Version ${prompt.version}: ${prompt.content}`))
  .catch(error => console.error(error));

PythonUsing requests library

import requests
import json

API_KEY = 'pm-your-api-key-here'
BASE_URL = 'https://prompthub.dev'

def get_prompt(username, repo_name, prompt_name, version=None):
    """Fetch a prompt by username, repository name, and prompt name."""
    url = f"{BASE_URL}/api/v1/repositories/{username}/{repo_name}/prompts/{prompt_name}"
    if version:
        url += f"?version={version}"
    
    headers = {
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # Raises an HTTPError for bad responses
        
        data = response.json()
        return data['prompt']
    
    except requests.exceptions.HTTPError as e:
        print(f"HTTP error occurred: {e}")
        print(f"Response: {response.text}")
        raise
    except requests.exceptions.RequestException as e:
        print(f"Request error occurred: {e}")
        raise

# Usage examples
try:
    # Get latest version of prompt
    prompt = get_prompt('john', 'my-project', 'welcome_message')
    print(f"Prompt content: {prompt['content']}")
    
    # Get specific version
    prompt_v3 = get_prompt('john', 'my-project', 'welcome_message', version=3)
    print(f"Version {prompt_v3['version']}: {prompt_v3['content']}")
    
except Exception as e:
    print(f"Error: {e}")

Best Practices

Store API keys securely

Use environment variables or secure key management systems. Never hardcode keys in your application.

Handle errors gracefully

Implement proper error handling for network issues, authentication failures, and missing prompts.

Use descriptive prompt IDs

Choose clear, descriptive names like user_welcome_email or error_notification.

Monitor API usage

Keep track of your API key usage and rotate keys periodically for security.

Prompt Versioning

Access different versions of your prompts using the version query parameter. By default, the API returns the latest version.

Latest Version

Without specifying a version parameter, you'll get the most recent version of the prompt.

Specific Version

Use ?version=3 to get a specific version number, useful for consistent deployments or rollbacks.

Repository Organization

Organize prompts by repository and use descriptive names for better maintainability and team collaboration.

Need Help?

If you're having trouble with the API or need additional features, we're here to help.