Skip to main content

Welcome to Potpie API

The Potpie API enables you to integrate AI-powered codebase intelligence into your applications, tools, and workflows. Our REST API provides programmatic access to all of Potpie’s core features including parsing, conversations, search, and agent interactions.

Getting Started

Base URL

All API requests should be made to:
https://production-api.potpie.ai

API Key

Get your API key from the Potpie Dashboard.
Keep your API key secure! Never commit it to version control or expose it in client-side code.

Making Your First Request

curl -X GET \
  'https://production-api.potpie.ai/api/v1/projects/list' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Authentication

All API endpoints require authentication using Bearer tokens. Include your API key in the Authorization header of every request:
Authorization: Bearer YOUR_API_KEY

Example Authentication

const response = await fetch('https://production-api.potpie.ai/api/v1/projects/list', {
  headers: {
    'Authorization': `Bearer ${process.env.POTPIE_API_KEY}`,
    'Content-Type': 'application/json'
  }
});

Security Best Practices

  • Store API keys in environment variables
  • Use different keys for development and production
  • Rotate keys periodically
  • Never log or print API keys
  • Implement proper error handling to avoid exposing keys

Available Endpoints

Parsing & Projects

Conversations & Agents

Integrations

Typical Workflow

Here’s a common workflow for using the Potpie API:

Step-by-Step Integration

1

Parse Your Repository

Use the Parse Directory endpoint to analyze your codebase and build the knowledge graph
2

Monitor Parsing

Poll the Get Parsing Status endpoint until parsing is complete
3

Select an Agent

Use List Agents to see available AI agents and choose the right one for your task
4

Create Conversation

Start a conversation with Create Conversation by providing project IDs and agent IDs
5

Interact

Send messages using Post Message and receive AI-powered responses about your codebase

Code Examples

Complete Integration Example

import fetch from 'node-fetch';

interface PotpieConfig {
  apiKey: string;
  baseUrl?: string;
}

class PotpieClient {
  private apiKey: string;
  private baseUrl: string;

  constructor(config: PotpieConfig) {
    this.apiKey = config.apiKey;
    this.baseUrl = config.baseUrl || 'https://production-api.potpie.ai';
  }

  private async request(endpoint: string, options: RequestInit = {}) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json',
        ...options.headers,
      },
    });

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

    return response.json();
  }

  // 1. Parse a repository
  async parseDirectory(data: {
    repo_name?: string;
    repo_path?: string;
    branch_name: string;
  }) {
    return this.request('/api/v1/parse', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  // 2. Check parsing status
  async getParsingStatus(projectId: string) {
    return this.request(`/api/v1/parsing-status/${projectId}`);
  }

  // 3. Wait for parsing to complete
  async waitForParsing(projectId: string, pollInterval = 5000) {
    while (true) {
      const status = await this.getParsingStatus(projectId);

      console.log(`Status: ${status.status} - ${status.progress}%`);

      if (status.status === 'ready') {
        return status;
      }

      if (status.status === 'failed') {
        throw new Error(`Parsing failed: ${status.error}`);
      }

      await new Promise(resolve => setTimeout(resolve, pollInterval));
    }
  }

  // 4. List all projects
  async listProjects() {
    return this.request('/api/v1/projects/list');
  }

  // 5. List available agents
  async listAgents() {
    return this.request('/api/v1/list-available-agents/');
  }

  // 6. Create a conversation
  async createConversation(data: {
    user_id: string;
    title: string;
    status: string;
    project_ids: string[];
    agent_ids: string[];
  }) {
    return this.request('/api/v1/conversations/', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  // 7. Send a message
  async postMessage(conversationId: string, content: string, nodeIds?: any[]) {
    return this.request(`/api/v1/conversations/${conversationId}/message/`, {
      method: 'POST',
      body: JSON.stringify({ content, node_ids: nodeIds }),
    });
  }

  // 8. Search codebase
  async searchCodebase(projectId: string, query: string) {
    return this.request('/api/v1/search', {
      method: 'POST',
      body: JSON.stringify({ project_id: projectId, query }),
    });
  }
}

// Usage example
async function main() {
  const client = new PotpieClient({
    apiKey: process.env.POTPIE_API_KEY!,
  });

  try {
    // Parse repository
    console.log('Starting repository parsing...');
    const parseResponse = await client.parseDirectory({
      repo_name: 'my-awesome-app',
      repo_path: '/path/to/repo',
      branch_name: 'main',
    });

    const projectId = parseResponse.project_id;
    console.log(`Project ID: ${projectId}`);

    // Wait for parsing to complete
    await client.waitForParsing(projectId);
    console.log('Parsing ready!');

    // List available agents
    const agents = await client.listAgents();
    console.log('Available agents:', agents);

    // Create conversation
    const conversation = await client.createConversation({
      user_id: 'user_123',
      title: 'Code Review Session',
      status: 'active',
      project_ids: [projectId],
      agent_ids: ['qna-agent'],
    });

    console.log(`Conversation ID: ${conversation.conversation_id}`);

    // Ask a question
    await client.postMessage(
      conversation.conversation_id,
      'How does authentication work in this codebase?'
    );

    console.log('Message sent successfully!');
  } catch (error) {
    console.error('Error:', error);
  }
}

main();

Rate Limits

To ensure fair usage and system stability:
ResourceLimit
API Requests1000 requests per hour
Parsing Jobs5 concurrent parsings
Message Rate10 messages per minute per conversation
Search Queries100 searches per minute
Rate limits are subject to your plan. Contact sales@potpie.ai for higher limits.

Error Handling

The API uses standard HTTP status codes:
Status CodeDescription
200Success
400Bad Request - Invalid parameters
401Unauthorized - Invalid or missing API key
403Forbidden - Insufficient permissions
404Not Found - Resource doesn’t exist
422Validation Error - Request body validation failed
429Too Many Requests - Rate limit exceeded
500Internal Server Error - Something went wrong

Error Response Format

{
  "detail": [
    {
      "loc": ["body", "project_id"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

Handling Errors

try {
  const response = await fetch(endpoint, options);

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('Invalid API key');
    }
    if (response.status === 429) {
      throw new Error('Rate limit exceeded - please wait before retrying');
    }
    if (response.status === 404) {
      throw new Error('Resource not found');
    }
    throw new Error(`API error: ${response.status}`);
  }

  return await response.json();
} catch (error) {
  console.error('API request failed:', error);
  throw error;
}

Best Practices

API Usage

  1. Polling: When checking parsing status, use exponential backoff to reduce unnecessary requests
  2. Caching: Cache project lists and agent information to minimize API calls
  3. Error Handling: Implement retry logic with exponential backoff for transient errors
  4. Timeouts: Set appropriate timeouts for long-running operations
  5. Pagination: Use pagination parameters when available to handle large result sets

Security

  1. API Keys: Store API keys securely in environment variables or secret management systems
  2. HTTPS: Always use HTTPS for API requests
  3. Key Rotation: Rotate API keys regularly
  4. Access Control: Use different API keys for different environments (dev, staging, prod)

Performance

  1. Batch Operations: Group related operations when possible
  2. Parallel Requests: Make independent API calls in parallel
  3. Response Caching: Cache responses when data doesn’t change frequently
  4. Connection Pooling: Reuse HTTP connections for multiple requests

SDKs and Libraries

Official SDKs (Coming Soon)

We’re working on official SDKs for:
  • TypeScript/JavaScript
  • Python
  • Go
  • Ruby

Community Libraries

Check out community-contributed libraries on GitHub.

Webhooks (Coming Soon)

Subscribe to events in your codebase:
  • Parsing ready
  • New conversation created
  • Message response ready
  • Code changes detected

Support

Need help?

API Changelog

Stay updated with the latest API changes:

2024-02-09

  • Comprehensive API documentation for 10 core endpoints
  • Enhanced OpenAPI 3.1 specification with detailed examples
  • Improved authentication and error handling documentation
  • Added complete integration examples in TypeScript and Python
  • Rate limiting and best practices guidelines
  • Added integrations endpoint for external service configuration
  • Streamlined conversation creation with direct message endpoint
Subscribe to our API changelog for updates.