openapi: "3.0.3"
info:
  title: InstantAPI
  description: >
    AI-powered utility API offering 6 tasks — summarize, extract, analyze,
    translate, sentiment, and code — all through a single endpoint at $0.50
    per call. Includes batch processing, webhook notifications, and
    rate-limited access with credit-based billing.
  version: "1.0.0"
  contact:
    name: InstantAPI Support
    email: support@instantapis.net
    url: https://instantapis.net
  termsOfService: https://instantapis.net/terms

servers:
  - url: https://instantapis.net
    description: Production

security:
  - bearerAuth: []

tags:
  - name: Generate
    description: Single AI task processing
  - name: Batch
    description: Process multiple AI tasks in one request
  - name: Webhooks
    description: Manage webhook endpoints and view delivery history

paths:
  # ── Generate ────────────────────────────────────────────────────────
  /api/v1/generate:
    post:
      summary: Process a single AI task
      description: >
        Send text to one of 6 AI tasks and receive structured results.
        Costs 1 credit ($0.50) per call. Responses are cached — identical
        requests return cached results without additional latency.
      operationId: generate
      tags: [Generate]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/GenerateRequest"
            examples:
              summarize:
                summary: Summarize text
                value:
                  task: summarize
                  input: "Artificial intelligence has transformed the way businesses operate. From automating routine tasks to providing deep insights from complex data sets, AI technologies are being adopted across every industry."
                  options:
                    length: short
              extract:
                summary: Extract structured data
                value:
                  task: extract
                  input: "Contact John Smith at john@example.com or call (555) 123-4567. He works as a Senior Engineer at Acme Corp."
                  options:
                    fields: [name, email, phone, title, company]
              analyze:
                summary: Analyze data for insights
                value:
                  task: analyze
                  input: "Q1 Revenue: $2.1M (up 15%), Q2 Revenue: $2.4M (up 14%), Q3 Revenue: $2.9M (up 21%), Q4 Revenue: $3.1M (up 7%)."
              translate:
                summary: Translate text
                value:
                  task: translate
                  input: "The quick brown fox jumps over the lazy dog."
                  options:
                    targetLanguage: spanish
              sentiment:
                summary: Analyze sentiment
                value:
                  task: sentiment
                  input: "I absolutely love this product! Best purchase I've made all year."
              code:
                summary: Generate code
                value:
                  task: code
                  input: "Write a function that checks if a string is a valid palindrome, ignoring spaces and punctuation"
                  options:
                    language: python
      responses:
        "200":
          description: Successful response
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/GenerateResponse"
              examples:
                summarize:
                  summary: Summarize response
                  value:
                    success: true
                    data:
                      summary: "AI is revolutionizing business operations through task automation and data-driven insights."
                    meta:
                      requestId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                      credits_remaining: 99
                sentiment:
                  summary: Sentiment response
                  value:
                    success: true
                    data:
                      sentiment: positive
                      confidence: 0.96
                      emotions:
                        joy: 0.85
                        trust: 0.78
                        surprise: 0.12
                        anger: 0.01
                      aspects:
                        - topic: product
                          sentiment: positive
                    meta:
                      requestId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                      credits_remaining: 98
          headers:
            X-Request-Id:
              schema:
                type: string
              description: Unique request identifier
            X-RateLimit-Limit:
              schema:
                type: integer
              description: Maximum requests per window
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: Remaining requests in current window
            X-RateLimit-Reset:
              schema:
                type: integer
              description: Unix timestamp when the rate limit resets
        "400":
          description: Invalid request (bad task type, missing input, or invalid JSON)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                success: false
                data: null
                error: "Invalid task. Must be: summarize, extract, analyze, translate, sentiment, code"
                meta:
                  requestId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                  credits_remaining: 100
        "401":
          description: Invalid or missing API key
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                success: false
                data: null
                error: "Invalid or missing API key."
                meta:
                  requestId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                  credits_remaining: 0
        "402":
          description: Insufficient credits
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                success: false
                data: null
                error: "Insufficient credits. Purchase more at /pricing."
                meta:
                  requestId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                  credits_remaining: 0
        "429":
          description: Rate limit exceeded or daily usage cap reached
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                success: false
                data: null
                error: "Rate limit exceeded."
                meta:
                  requestId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                  credits_remaining: 50
          headers:
            Retry-After:
              schema:
                type: integer
              description: Seconds until rate limit resets
        "502":
          description: AI processing failed (credit is refunded)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                success: false
                data: null
                error: "AI processing failed. Credit refunded."
                meta:
                  requestId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                  credits_remaining: 100

    get:
      summary: Get generate endpoint info
      description: Returns information about the generate endpoint including supported tasks and usage instructions.
      operationId: generateInfo
      tags: [Generate]
      security: []
      responses:
        "200":
          description: Endpoint information
          content:
            application/json:
              schema:
                type: object

  # ── Batch ───────────────────────────────────────────────────────────
  /api/v1/batch:
    post:
      summary: Process multiple AI tasks in one request
      description: >
        Send up to 20 tasks in a single request. Tasks are processed
        concurrently (max 5 in parallel). Each task costs 1 credit ($0.50).
        Credits are deducted upfront and refunded for any failed tasks.
      operationId: batch
      tags: [Batch]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BatchRequest"
            example:
              tasks:
                - id: req_1
                  task: summarize
                  input: "Long article text..."
                - id: req_2
                  task: sentiment
                  input: "I love this product!"
                - id: req_3
                  task: extract
                  input: "John at john@example.com"
                  options:
                    fields: [name, email]
      responses:
        "200":
          description: Batch completed (individual tasks may have failed)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BatchResponse"
              example:
                success: true
                data:
                  results:
                    - id: req_1
                      success: true
                      data:
                        summary: "Article summary here."
                    - id: req_2
                      success: true
                      data:
                        sentiment: positive
                        confidence: 0.95
                    - id: req_3
                      success: true
                      data:
                        name: John
                        email: john@example.com
                  summary:
                    total: 3
                    succeeded: 3
                    failed: 0
                meta:
                  requestId: "batch_a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                  credits_remaining: 97
                  totalLatencyMs: 2340
          headers:
            X-Request-Id:
              schema:
                type: string
              description: Unique batch request identifier (prefixed with batch_)
        "400":
          description: Invalid request (empty tasks array, exceeds 20, bad task types)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                success: false
                data: null
                error: "Maximum 20 tasks per batch."
                meta:
                  requestId: "batch_a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                  credits_remaining: 100
        "401":
          description: Invalid or missing API key
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
        "402":
          description: Insufficient credits for all tasks
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"
              example:
                success: false
                data: null
                error: "Insufficient credits. Need 3, have 1."
                meta:
                  requestId: "batch_a1b2c3d4-e5f6-7890-abcd-ef1234567890"
                  credits_remaining: 1
        "429":
          description: Rate limit exceeded
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ErrorResponse"

    get:
      summary: Get batch endpoint info
      description: Returns information about the batch endpoint including max batch size, concurrency, and supported tasks.
      operationId: batchInfo
      tags: [Batch]
      security: []
      responses:
        "200":
          description: Batch endpoint information
          content:
            application/json:
              schema:
                type: object

  # ── Webhooks ────────────────────────────────────────────────────────
  /api/webhooks:
    get:
      summary: List webhook endpoints
      description: Returns all webhook endpoints configured for the authenticated user.
      operationId: listWebhooks
      tags: [Webhooks]
      security:
        - sessionAuth: []
      responses:
        "200":
          description: List of webhook endpoints
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  data:
                    type: object
                    properties:
                      endpoints:
                        type: array
                        items:
                          $ref: "#/components/schemas/WebhookEndpoint"
              example:
                success: true
                data:
                  endpoints:
                    - id: "wh_abc123"
                      url: "https://example.com/webhook"
                      events:
                        - task.completed
                        - task.failed
                      active: true
                      createdAt: "2026-03-01T00:00:00.000Z"
                      updatedAt: "2026-03-01T00:00:00.000Z"
                      _count:
                        deliveries: 42
        "401":
          description: Authentication required (session-based)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"

    post:
      summary: Create a webhook endpoint
      description: >
        Register a new webhook endpoint to receive event notifications.
        Maximum 10 endpoints per user. The webhook secret is returned only
        once on creation — store it securely for HMAC signature verification.
      operationId: createWebhook
      tags: [Webhooks]
      security:
        - sessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateWebhookRequest"
            example:
              url: "https://example.com/webhook"
              events:
                - task.completed
                - task.failed
                - credits.low
      responses:
        "201":
          description: Webhook endpoint created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                      url:
                        type: string
                      events:
                        type: array
                        items:
                          type: string
                      active:
                        type: boolean
                      secret:
                        type: string
                        description: HMAC signing secret. Shown only once.
                      message:
                        type: string
              example:
                success: true
                data:
                  id: "wh_abc123"
                  url: "https://example.com/webhook"
                  events:
                    - task.completed
                    - task.failed
                    - credits.low
                  active: true
                  secret: "whsec_abc123def456..."
                  message: "Store this secret securely. It will not be shown again."
        "400":
          description: Invalid request (bad URL, missing events, max endpoints reached)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"
        "401":
          description: Authentication required
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"

    patch:
      summary: Update a webhook endpoint
      description: >
        Update an existing webhook endpoint's URL, subscribed events, or
        active status. Only provided fields are updated.
      operationId: updateWebhook
      tags: [Webhooks]
      security:
        - sessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/UpdateWebhookRequest"
            example:
              id: "wh_abc123"
              events:
                - task.completed
                - batch.completed
              active: true
      responses:
        "200":
          description: Webhook endpoint updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                      url:
                        type: string
                      events:
                        type: array
                        items:
                          type: string
                      active:
                        type: boolean
                      updatedAt:
                        type: string
                        format: date-time
              example:
                success: true
                data:
                  id: "wh_abc123"
                  url: "https://example.com/webhook"
                  events:
                    - task.completed
                    - batch.completed
                  active: true
                  updatedAt: "2026-03-28T12:00:00.000Z"
        "400":
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"
        "401":
          description: Authentication required
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"
        "404":
          description: Webhook endpoint not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"

    delete:
      summary: Delete a webhook endpoint
      description: Permanently remove a webhook endpoint and all its delivery history.
      operationId: deleteWebhook
      tags: [Webhooks]
      security:
        - sessionAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id:
                  type: string
                  description: ID of the webhook endpoint to delete
            example:
              id: "wh_abc123"
      responses:
        "200":
          description: Webhook endpoint deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                      message:
                        type: string
              example:
                success: true
                data:
                  id: "wh_abc123"
                  message: "Webhook endpoint deleted."
        "400":
          description: Missing endpoint ID
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"
        "401":
          description: Authentication required
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"
        "404":
          description: Webhook endpoint not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"

  # ── Webhook Deliveries ──────────────────────────────────────────────
  /api/webhooks/deliveries:
    get:
      summary: List recent webhook deliveries
      description: >
        Returns the 10 most recent delivery attempts for a specific
        webhook endpoint. Useful for debugging delivery failures.
      operationId: listWebhookDeliveries
      tags: [Webhooks]
      security:
        - sessionAuth: []
      parameters:
        - name: endpointId
          in: query
          required: true
          description: The webhook endpoint ID to fetch deliveries for
          schema:
            type: string
      responses:
        "200":
          description: List of recent deliveries
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      deliveries:
                        type: array
                        items:
                          $ref: "#/components/schemas/WebhookDelivery"
              example:
                success: true
                data:
                  deliveries:
                    - id: "del_xyz789"
                      event: task.completed
                      status: delivered
                      statusCode: 200
                      attempts: 1
                      lastAttemptAt: "2026-03-28T11:30:00.000Z"
                      createdAt: "2026-03-28T11:30:00.000Z"
                    - id: "del_xyz790"
                      event: task.failed
                      status: failed
                      statusCode: 500
                      attempts: 3
                      lastAttemptAt: "2026-03-28T11:35:00.000Z"
                      createdAt: "2026-03-28T11:32:00.000Z"
        "400":
          description: Missing endpointId query parameter
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"
        "401":
          description: Authentication required
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"
        "404":
          description: Webhook endpoint not found
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebhookErrorResponse"

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >
        API key starting with `ia_live_`. Used for /api/v1/* endpoints.
        Obtain one at https://instantapis.net/dashboard
    sessionAuth:
      type: apiKey
      in: cookie
      name: next-auth.session-token
      description: >
        Session cookie set after signing in via the web dashboard.
        Used for /api/webhooks/* endpoints.

  schemas:
    # ── Generate ──────────────────────────────────────────────────────
    GenerateRequest:
      type: object
      required: [task, input]
      properties:
        task:
          type: string
          enum: [summarize, extract, analyze, translate, sentiment, code]
          description: The AI task to perform
        input:
          type: string
          minLength: 1
          description: The text to process
        options:
          type: object
          description: Task-specific options (varies by task)
          properties:
            length:
              type: string
              enum: [short, medium, long]
              description: "Summary length (summarize task only). Defaults to \"medium\"."
            fields:
              type: array
              items:
                type: string
              description: "Fields to extract (extract task only). e.g. [\"name\", \"email\"]"
            targetLanguage:
              type: string
              description: "Target language (translate task only). e.g. \"spanish\", \"french\""
            language:
              type: string
              description: "Programming language (code task only). e.g. \"python\", \"javascript\""

    GenerateResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          description: Task-specific result data (structure varies by task)
        meta:
          $ref: "#/components/schemas/Meta"

    # ── Batch ─────────────────────────────────────────────────────────
    BatchRequest:
      type: object
      required: [tasks]
      properties:
        tasks:
          type: array
          minItems: 1
          maxItems: 20
          description: Array of tasks to process (max 20)
          items:
            $ref: "#/components/schemas/BatchTask"

    BatchTask:
      type: object
      required: [task, input]
      properties:
        id:
          type: string
          description: Optional client-provided ID for correlation. Auto-assigned as task_0, task_1, etc. if omitted.
        task:
          type: string
          enum: [summarize, extract, analyze, translate, sentiment, code]
        input:
          type: string
          minLength: 1
        options:
          type: object
          description: Task-specific options (same as GenerateRequest.options)

    BatchResponse:
      type: object
      properties:
        success:
          type: boolean
        data:
          type: object
          properties:
            results:
              type: array
              items:
                $ref: "#/components/schemas/BatchResult"
            summary:
              type: object
              properties:
                total:
                  type: integer
                  description: Total tasks submitted
                succeeded:
                  type: integer
                  description: Number of successfully completed tasks
                failed:
                  type: integer
                  description: Number of failed tasks (credits refunded)
        meta:
          type: object
          properties:
            requestId:
              type: string
              description: Unique batch request ID (prefixed with batch_)
            credits_remaining:
              type: integer
            totalLatencyMs:
              type: integer
              description: Total wall-clock time for the batch in milliseconds

    BatchResult:
      type: object
      properties:
        id:
          type: string
          description: Task ID (client-provided or auto-generated)
        success:
          type: boolean
        data:
          type: object
          nullable: true
          description: Task result data, or null on failure
        error:
          type: string
          description: Error message (only present on failure)

    # ── Webhooks ──────────────────────────────────────────────────────
    WebhookEndpoint:
      type: object
      properties:
        id:
          type: string
        url:
          type: string
          format: uri
        events:
          type: array
          items:
            $ref: "#/components/schemas/WebhookEventType"
        active:
          type: boolean
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
        _count:
          type: object
          properties:
            deliveries:
              type: integer

    WebhookDelivery:
      type: object
      properties:
        id:
          type: string
        event:
          $ref: "#/components/schemas/WebhookEventType"
        status:
          type: string
          description: "Delivery status (e.g. delivered, failed, pending)"
        statusCode:
          type: integer
          nullable: true
          description: HTTP status code returned by the webhook receiver
        attempts:
          type: integer
          description: Number of delivery attempts
        lastAttemptAt:
          type: string
          format: date-time
          nullable: true
        createdAt:
          type: string
          format: date-time

    WebhookEventType:
      type: string
      enum:
        - task.completed
        - task.failed
        - batch.completed
        - credits.low
        - credits.depleted
      description: >
        Available webhook event types:
        - task.completed: Fired when a single generate task succeeds
        - task.failed: Fired when a single generate task fails
        - batch.completed: Fired when a batch request finishes
        - credits.low: Fired when credits drop to 2 or below
        - credits.depleted: Fired when credits reach 0

    CreateWebhookRequest:
      type: object
      required: [url, events]
      properties:
        url:
          type: string
          format: uri
          description: HTTPS URL that will receive webhook POST requests
        events:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/WebhookEventType"
          description: Event types to subscribe to

    UpdateWebhookRequest:
      type: object
      required: [id]
      properties:
        id:
          type: string
          description: ID of the webhook endpoint to update
        url:
          type: string
          format: uri
          description: New URL (optional)
        events:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/WebhookEventType"
          description: New event subscriptions (optional)
        active:
          type: boolean
          description: Enable or disable the endpoint (optional)

    # ── Shared ────────────────────────────────────────────────────────
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        data:
          nullable: true
          example: null
        error:
          type: string
          description: Human-readable error message
        meta:
          $ref: "#/components/schemas/Meta"

    WebhookErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          description: Human-readable error message

    Meta:
      type: object
      properties:
        requestId:
          type: string
          description: Unique request identifier for debugging
        credits_remaining:
          type: integer
          description: Credits remaining after this request
