> ## Documentation Index
> Fetch the complete documentation index at: https://docs.initrepo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> InitRepo REST API - Programmatic Project Generation

<Note>
  **🚀 API Now Available**

  The InitRepo REST API is now live and provides programmatic access to AI-powered project generation with credit-based billing.
</Note>

## Overview

The InitRepo API provides comprehensive programmatic access to AI-powered project generation capabilities:

### Key Features

* **AI-Powered Generation**: Create comprehensive software project documentation automatically
* **Credit-Based Billing**: Transparent pricing with automatic refunds for failed generations
* **Async Processing**: Non-blocking project generation with status polling
* **Webhook Support**: Real-time notifications for project completion
* **Enterprise Security**: Multiple layers of security including XSS protection and SSRF prevention

### Base Information

| Property             | Value                                                                                           |
| -------------------- | ----------------------------------------------------------------------------------------------- |
| **Base URL**         | `https://api.initrepo.com/v1` (production)<br />`https://dev-api.initrepo.com/v1` (development) |
| **Protocol**         | HTTPS (TLS 1.3+)                                                                                |
| **Authentication**   | Bearer token with API keys                                                                      |
| **Rate Limiting**    | 100 requests per minute per API key                                                             |
| **Content-Type**     | `application/json`                                                                              |
| **Credit Cost**      | 15,000 credits per project generation                                                           |
| **API Version**      | v1.0 (current stable)                                                                           |
| **Interactive Docs** | [Swagger UI](https://api.initrepo.com/v1/docs)                                                  |

## API Versioning

InitRepo API uses semantic versioning to ensure backward compatibility and smooth upgrades:

### Version Methods

You can specify the API version using any of these methods:

#### 1. URL-based Versioning (Recommended)

```javascript theme={null}
// Use version in URL path
https://api.initrepo.com/v1/projects
```

#### 2. Accept Header

```javascript theme={null}
const headers = {
  'Authorization': 'Bearer ir_live_your_api_key',
  'Accept': 'application/vnd.initrepo.v1+json'
};
```

#### 3. API-Version Header

```javascript theme={null}
const headers = {
  'Authorization': 'Bearer ir_live_your_api_key',
  'API-Version': 'v1.0'
};
```

### Supported Versions

| Version | Status  | Support Level | Sunset Date |
| ------- | ------- | ------------- | ----------- |
| v1.0    | Current | Full support  | -           |
| v1.1    | Future  | Not available | -           |
| v2.0    | Future  | Not available | -           |

### Version Headers

All API responses include versioning information:

```javascript theme={null}
// Response headers
API-Version: v1.0
API-Supported-Versions: v1.0
API-Latest-Version: v1.0
X-Request-ID: req_1234567890
```

## Authentication

### API Keys

InitRepo uses Bearer token authentication with cryptographically secure API keys:

#### Live Keys (`ir_live_*`)

* **Format**: `ir_live_[32-character-string]`
* **Usage**: Production environment, consumes actual credits
* **Cost**: 15,000 credits per project generation
* **Limit**: Maximum 3 keys per user

#### Test Keys (`ir_test_*`)

* **Format**: `ir_test_[32-character-string]`
* **Usage**: Development/testing environment
* **Cost**: Free (no credits consumed)
* **Limit**: Maximum 3 keys per user

<Warning>
  **API Key Limits**

  Each user can create a maximum of **3 API keys** (combined live and test keys). This production limit ensures security and proper usage monitoring. If you reach this limit, you'll need to delete existing keys before creating new ones.
</Warning>

```javascript theme={null}
const headers = {
  'Authorization': 'Bearer ir_live_your_api_key_here',
  'Content-Type': 'application/json',
  'API-Version': 'v1.0'
};
```

### Authentication Errors

| Error Code              | Status | Description                    | Resolution                                  |
| ----------------------- | ------ | ------------------------------ | ------------------------------------------- |
| `AUTHENTICATION_FAILED` | 401    | Invalid or missing API key     | Check your API key format and validity      |
| `MAX_KEYS_REACHED`      | 403    | Maximum API keys limit reached | Delete unused keys before creating new ones |

### Best Practices

* **Rotate Keys Regularly**: Update API keys periodically for security
* **Use Test Keys**: Always test with `ir_test_*` keys before going live
* **Secure Storage**: Never commit API keys to version control
* **Monitor Usage**: Track API key usage through the dashboard

## Core Endpoints

### Create Project

```javascript theme={null}
// Create a new project for AI-powered generation
const response = await fetch('https://api.initrepo.com/v1/projects', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ir_live_your_api_key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    projectIdea: 'Build a modern e-commerce platform with AI recommendations',
    projectType: 'web',
    features: [
      {
        name: 'Product Catalog',
        description: 'Display products with search and filtering capabilities'
      }
    ],
    integrations: ['stripe', 'sendgrid'],
    format: 'full',
    webhookUrl: 'https://your-app.com/webhooks/initrepo'
  })
});
```

### Get Project Status

```javascript theme={null}
// Check project generation status
const response = await fetch('https://api.initrepo.com/v1/projects/{projectId}', {
  headers: {
    'Authorization': 'Bearer ir_live_your_api_key'
  }
});
```

## Rate Limits

The API enforces rate limits to ensure fair usage and system stability:

* **Requests per Minute**: 100 per API key
* **Credit Cost**: 15,000 credits per project
* **Test Mode**: Free access with test keys

### Rate Limit Headers

All API responses include rate limiting information:

```javascript theme={null}
// Response headers
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1699123456  // Unix timestamp
```

### Handling Rate Limits

When you exceed the rate limit, you'll receive a `429 Too Many Requests` response:

```json theme={null}
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Try again in 60 seconds.",
    "request_id": "req_1234567890",
    "details": {
      "retry_after": 60,
      "limit": 100,
      "window": "1 minute"
    }
  }
}
```

### Best Practices

* **Monitor Headers**: Check `X-RateLimit-Remaining` to avoid hitting limits
* **Implement Backoff**: Use exponential backoff when approaching limits
* **Batch Operations**: Combine multiple operations when possible

## Error Handling

The InitRepo API uses standardized error responses with consistent structure and helpful debugging information.

### Error Response Format

All errors follow this consistent format:

```json theme={null}
{
  "success": false,
  "error": {
    "code": "AUTHENTICATION_FAILED",
    "message": "Invalid API key provided",
    "request_id": "req_1234567890",
    "documentation": "https://docs.initrepo.com/api/authentication",
    "details": {
      "field": "authorization_header",
      "issue": "malformed_key"
    }
  }
}
```

### Standard Error Codes

| Code                    | Status | Description                      | Resolution                            |
| ----------------------- | ------ | -------------------------------- | ------------------------------------- |
| `AUTHENTICATION_FAILED` | 401    | Invalid or missing API key       | Verify API key format and validity    |
| `RATE_LIMIT_EXCEEDED`   | 429    | Too many requests                | Wait for rate limit reset             |
| `INVALID_JSON`          | 400    | Malformed JSON in request body   | Check JSON syntax and structure       |
| `VALIDATION_ERROR`      | 422    | Request data validation failed   | Review field requirements and formats |
| `RESOURCE_NOT_FOUND`    | 404    | Requested resource doesn't exist | Check resource ID and permissions     |
| `SECURITY_VIOLATION`    | 403    | Request blocked for security     | Review request content and patterns   |
| `INTERNAL_ERROR`        | 500    | Server-side processing error     | Contact support with request ID       |

### Error Handling Best Practices

#### 1. Check the Status Code

```javascript theme={null}
if (!response.ok) {
  const error = await response.json();
  console.error(`API Error: ${error.error.code} - ${error.error.message}`);
}
```

#### 2. Use Request IDs for Support

Always include the `request_id` when contacting support:

```javascript theme={null}
const errorData = await response.json();
console.log(`Request ID for support: ${errorData.error.request_id}`);
```

#### 3. Implement Proper Retry Logic

```javascript theme={null}
async function makeAPIRequest(url, options, retries = 3) {
  try {
    const response = await fetch(url, options);
    
    if (response.status === 429) {
      // Rate limited - check retry after header
      const retryAfter = response.headers.get('retry-after') || 60;
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      return makeAPIRequest(url, options, retries - 1);
    }
    
    return response;
  } catch (error) {
    if (retries > 0) {
      await new Promise(resolve => setTimeout(resolve, 1000));
      return makeAPIRequest(url, options, retries - 1);
    }
    throw error;
  }
}
```

### Common Error Scenarios

#### Authentication Errors

```json theme={null}
{
  "success": false,
  "error": {
    "code": "AUTHENTICATION_FAILED",
    "message": "Invalid API key format",
    "details": {
      "expected_format": "ir_live_ or ir_test_ followed by 32 characters"
    }
  }
}
```

#### Validation Errors

```json theme={null}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Required field missing",
    "details": {
      "missing_fields": ["projectIdea"],
      "invalid_fields": {
        "projectType": "Must be one of: web, mobile, api, desktop"
      }
    }
  }
}
```

## Use Cases

### Automation & CI/CD

* **Automated Documentation**: Generate project docs as part of your development workflow
* **Quality Assurance**: Ensure comprehensive documentation for all projects
* **Version Control**: Keep documentation in sync with code changes

### Custom Integrations

* **Project Management**: Sync with Jira, Linear, or custom PM tools
* **AI Workflows**: Use generated documentation to power custom AI tools
* **Reporting**: Build custom dashboards and analytics

### Enterprise Workflows

* **Bulk Operations**: Manage multiple projects across teams
* **Custom Templates**: Apply organization-specific documentation standards
* **Compliance**: Meet regulatory requirements through standardized processes

## SDKs & Libraries

Official SDKs are available for popular languages:

* **JavaScript/TypeScript** - `npm install initrepo-api`
* **Python** - `pip install initrepo-api`
* **Go** - `go get github.com/initrepo/initrepo-go`
* **Java** - Maven/Gradle packages available

## Getting Started

1. **Get API Keys**: Sign up at [https://initrepo.com](https://initrepo.com) and generate API keys
2. **Test Integration**: Use test keys (`ir_test_*`) for development
3. **Go Live**: Switch to live keys (`ir_live_*`) for production

<Info>
  **Need Help?**

  Join our [Discord community](https://discord.gg/7HJmEzrY4d) for support, or check out the detailed endpoint documentation below.
</Info>
