openapi: 3.1.0
info:
  title: img.pro API
  description: |
    App image storage API. Upload images into App or connected-user storage.

    ## Quick start

    Open [Apps](https://img.pro/apps), create an App, then open its API Keys page
    and choose New key. Save the key shown once and authenticate every request
    with it:

    ```bash
    curl -X POST https://api.img.pro/v1/images \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -F "file=@screenshot.png"
    ```

    ## Authentication

    ```
    Authorization: Bearer YOUR_API_KEY
    ```

    A key's reach is App-wide or App storage only (scope `app` or
    `bucket`). App-wide keys use the App storage when X-Img-User is absent.
    A present X-Img-User selects that connected user's storage within the
    App. Blank or malformed selectors fail with 422; unavailable or
    unconnected users fail with 403 user_forbidden. There is no fallback after
    a selector error. A key that is not
    App-wide rejects X-Img-User (422). All keys carry read and/or write
    permissions. Keep keys server-side.

    ## Changes

    **Pro has limits, and Unlimited is new (spec 4.10.0).** An App's img.pro
    plan is now Free, Pro or Unlimited, so `plan` can be `unlimited`:
    treat a value you don't know as a safe default and read `limits`. Pro
    now holds an App to 50,000 images and 500 users. On Pro,
    `limits_enforced` and `X-Limits-Enforced` are `true`, `limits`
    carries those numbers, a create at the images limit answers
    `403 quota_exceeded` and stores nothing, and a new user's first
    sign-in at the users limit is refused, as on Free. Unlimited has no
    limits: `limits_enforced` is `false` and both limits are null.

    **One original for everyone; only image extensions load (spec 4.9.0).**
    An image's original, at a URL with no valid transform parameter, is the
    same re-encoded copy for every request: a signed-in member of the
    image's team no longer gets the file as uploaded. A URL whose extension
    is not `jpg`, `jpeg`, `png`, `gif`, `webp` or `avif`, in any
    case, answers `404`: a `.heic` or `.heif` URL no longer redirects
    (`308`) to `.jpg`, and another extension no longer answers `400`
    to a transform, nor an image to a `format` override. A HEIC upload's
    `url` still ends in `.jpg`. A `metadata` parameter is ignored, as any
    unsupported parameter is, so an image whose saved presentation carried
    it no longer shows it in `url` and `sizes`; the old URLs keep
    working.

    **New transformations may be limited (spec 4.8.0).** To prevent abuse, the
    CDN may answer a new transformation of an image with `429` and a short
    message for a while. Its named sizes, its original and the versions already
    made keep working; write to support@img.pro if it gets in your way.

    **Effects and watermark retired (spec 4.8.0).** `fx`, `strength` and
    `tile` are no longer transform parameters. A URL that still carries them
    is served as the same URL without them, as any unsupported parameter is.

    **Original files re-encoded without their embedded metadata.** Changed October 1, 2026 (spec 4.7.0). An image's original, at a URL with no valid transform parameter, is no longer served as uploaded: it is a high-quality copy re-encoded in the same format (lossless for PNG, though an animated PNG becomes a still image; animation kept for GIF and WebP), so its `Content-Length` is the copy's, not the image's `bytes`. Public images carry pixels only: no public image carries location, camera or device details, capture time, edit history, embedded previews or provenance manifests. Their color is converted to sRGB, and an original's rotation is applied to its pixels. Downloaded with download=1, an original keeps the name it was uploaded with, which may record when it was taken. Each original's `ETag` changes once, so a client downloads it once more. The file you uploaded is never changed. An original that cannot be decoded is not served (`422`). `download=1` saves a transformed image, a converted format included, as `{id}.{ext}`; the original keeps the name it was uploaded with. From October 1, 2026, a signed-in member of the image's team got the file as uploaded and a `.heic` or `.heif` URL answered `308`; since spec 4.9.0 everyone gets this copy and such a URL answers `404`.

    **Billing status now reads one user.** Changed September 29, 2026 (spec 4.6.0). `GET /v1/billing/status` no longer answers with an img.pro plan and usage, with or without `X-Img-User` (your App storage's, or that user's). It reads one user's subscription to the plans your App sells, with an App-wide key and `X-Img-User` or with that user's own key, and its `billing_url` opens that user's billing card. With a user, its body is new: `plan`, `usage`, `limits_enforced` and `available_plans` are gone; read `access` and `subscription`. Called without a user, it answers `403 forbidden` with a message that says so. Your App's img.pro plan and usage are at `GET /v1/usage` (`plan` and `limits`), and you manage the plan on Billing in the console. New: `GET /v1/billing/plans` lists the plans your App sells, each with its prices on sale, in the Display order you set in Pricing (`display_order`).

    **Images no longer have a visibility setting.** Changed September 29, 2026 (spec 4.4.0). Every image loads from its `url` for anyone holding the link, and the viewer page is retired. Responses no longer include `public` or `page_url`. Requests that still send `public` are accepted and ignored until November 1, 2026; from that date they get `422 validation_error` naming the field, so remove it before then. A `page_url` you saved still redirects: to the file for an image that was public before this change, and to the img.pro home page for any other, so show or share `url` instead. `GET /v1/images/{id}` now needs a key with read access to the image's App, like every other endpoint; without one it answers `401 unauthorized`.

    ## Plans and limits

    Free: up to 5,000 images and 50 users per App. Pro: up to 50,000 images and 500 users per App, $20 a month. Unlimited: no limits, $100 a month.

    The limits count the whole App: the images in its storage and in every
    connected user's, and its users. On Free, at
    5,000 stored images a new upload or URL import is refused
    with `403 quota_exceeded` (`quota_error`) and stores nothing, and at
    50 users a new user's first sign-in through img.pro is refused.
    Pro does the same at 50,000 images and 500 users. Unlimited has no
    limits. Everything already stored keeps serving, and every user already
    connected keeps signing in. Upgrade the App in Billing: Free to Pro, Pro
    to Unlimited. `GET /v1/usage` reports the App's plan and both counts
    against their limits (`limits_enforced: true` on Free and Pro, `false`
    on Unlimited). Technical, authorization, and lifecycle checks apply on
    every plan alike.

    ## Response headers

    Authenticated responses include the storage's usage with monthly upload
    and storage limit values, which are informational and never refuse anything. Creates
    and `GET /v1/usage` also carry `X-Limits-Enforced`: `true` on Free
    and Pro, whose limits apply, and `false` on Unlimited.
    ```
    X-Limits-Enforced: true
    X-Monthly-Uploads-Used: 42
    X-Monthly-Uploads-Limit: 1000
    X-Monthly-Uploads-Remaining: 958
    X-Storage-Used: 52428800
    X-Storage-Limit: 10737418240
    X-Storage-Remaining: 10684989440
    ```

    Do not use the per-storage remaining values to block uploads; the App's
    limits are on `GET /v1/usage` (`limits`).

    ## Error responses

    Every error is one nested `error` object: branch on `error.type`
    (coarse category) or switch on `error.code` (specific):
    ```json
    {
      "error": {
        "type": "rate_limit_error",
        "code": "rate_limited",
        "message": "Human-readable explanation",
        "action": { "type": "wait", "retry_after": 60 }
      }
    }
    ```

    `error.type` is one of `invalid_request_error`, `authentication_error`,
    `permission_error`, `rate_limit_error`, `quota_error`,
    `idempotency_error`, `processing_error`, `api_error`. The optional
    `error.action` tells you exactly what to do next. `quota_exceeded`
    (`quota_error`, 403) is a create refused at the App's images limit:
    5,000 on Free, 50,000 on Pro.

    ## Blocked Apps

    While an App is blocked, every write from the App's own keys (any
    method but GET, HEAD or OPTIONS) is refused, until the block is lifted.
    Write to support@img.pro. An App-storage key gets
    `403 app_blocked` (`permission_error`) on a write and keeps reading.
    App-wide keys answer `403 app_suspended` to every request, reads and
    writes alike, as they do while the App is paused. A connected user's own
    key is not the App's, and keeps working as it does while the App is
    paused.

    ## Image links & transforms

    `url` is the image itself: a direct, embeddable CDN URL (always
    present), and the link to use wherever you show or share
    the image. Anyone with it can load the image. Append query parameters to
    transform it on the fly. `sizes` carries three ready-made responsive
    variants (small/medium/large); for a social/OG card, add
    `?size=social` to the `url`.

    Apply transforms to `url` (the `GET /{prefix}/{filename}` operation
    below documents every parameter). Named sizes: `?size=s|m|l|social`
    (short side 320/640/1080px, or a 1200×630 OG card). Format override:
    `?format=jpg|webp|avif|png|gif` (overrides the path extension). Dimensions:
    `?w=`, `?h=` (1–4096), `?fit=scale-down|contain|cover|crop|pad|squeeze`,
    `?gravity=auto|face|...`, `?zoom=` (0–1). Quality: `?q=` (1–100, or
    `high|medium-high|medium-low|low`). Color/tone (decimal multipliers
    centered at 1, range 0–10, omit for no change): `?brightness=`,
    `?contrast=`, `?gamma=` (>1 darkens midtones, <1 lightens), `?saturation=`
    (0 = grayscale). Filters: `?blur=` (integer 0–250), `?sharp=` (decimal
    0–10). Orientation: `?rotate=90|180|270`, `?flip=h|v|hv`, `?trim=border`.
    Background: `?segment=foreground` (remove),
    `?background=white|%23hex|rgb(...)|rgba(...)` (fill transparent areas).
    Download: `?download=1` saves the file, the original under the
    name it was uploaded with and a transformed image as `{id}.{ext}`.
    Privacy: Public images carry pixels only: no public image carries location, camera or device details, capture time, edit history, embedded previews or provenance manifests. Their color is converted to sRGB, and an original's rotation is applied to its pixels. Downloaded with download=1, an original keeps the name it was uploaded with, which may record when it was taken. A HEIC
    upload's `url` ends in `.jpg`, and a `.heic` or `.heif` URL
    answers 404, as any extension other than `jpg`, `jpeg`, `png`,
    `gif`, `webp` or `avif` does. See /api/transforms for the full
    reference with examples.

  version: 4.10.0
  contact:
    name: img.pro
    url: https://img.pro
    email: api@img.pro
  license:
    name: img.pro API Terms of Service
    url: https://img.pro/terms

servers:
  - url: https://api.img.pro
    description: img.pro API

tags:
  - name: Images
    description: Store and manage images
  - name: Usage
    description: Read your storage's usage and your App's img.pro plan
  - name: Transforms
    description: |
      Resize, convert, crop, and edit images on the fly via query parameters on
      the CDN `url`. No key and no extra API call: see GET /{prefix}/{filename}.
  - name: App
    description: |
      img.pro sign-in and connected-user storage for Apps. The same App-wide
      key selects App storage by default or a connected user's storage with
      X-Img-User. See /api/app.
  - name: Billing
    description: The plans your App sells and what each of its users has, read-only.

paths:
  /v1/usage:
    get:
      tags: [Usage]
      summary: Read Usage
      description: |
        Read the selected storage's usage (`monthly`, `totals`) and the
        App's plan with its limits (`plan`, `limits_enforced`, `limits`).
        `limits` counts the whole App, its storage and every connected
        user's, whichever storage the key selects: on Free and Pro, creates are
        refused once `limits.images.used` reaches `limits.images.limit`, and
        first sign-ins once `limits.users.used` reaches `limits.users.limit`;
        on Unlimited both limits are null. The monthly upload and storage limit values
        (`monthly.uploads_limit`, `totals.storage_limit_bytes`) are
        informational and must not gate uploads. For an App-wide key, omit
        X-Img-User for App storage or supply a connected user id for their storage.
      operationId: getUsage
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/XImgUser'
      responses:
        '200':
          description: Current usage
          headers:
            X-Limits-Enforced:
              $ref: '#/components/headers/X-Limits-Enforced'
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UsageResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

  /v1/images:
    post:
      tags: [Images]
      summary: Create Image
      description: |
        Create an image from a file (multipart) or a URL (JSON): one endpoint,
        two sources, negotiated by Content-Type. Authentication is required via
        an API key, with optional `X-Img-User` for App-wide keys.

        **File upload (multipart/form-data):**
        **Formats:** JPEG, PNG, GIF, WebP, AVIF, and supported HEVC-based HEIC
        **Limit:** every file must be at most 20 MB (20,000,000 bytes)
        and decode in img.pro's image processor, checked before any Image is created.
        A .heif filename/MIME alias is accepted only when the bytes contain
        supported HEVC HEIC.
        A file that is too large or does not decode returns `422 validation_error`
        under `details.file`; a failure of img.pro's image processor returns a
        retryable `500 upload_failed` / `import_failed`. A rejected upload
        stores nothing. SVG, BMP, and ICO are not accepted.

        **URL import (application/json):** supply a `url` and we fetch it
        server-side (30s timeout, follows redirects). Same response as a file
        upload.

        **Retry-safety:** send an `Idempotency-Key` header to make a create
        safe to retry. A replay with the same key + body returns the original
        response verbatim (`Idempotent-Replayed: true`); the same key with a
        different body → `409 idempotency_key_conflict`; the same key while the
        original is still in flight → `409 idempotency_key_in_progress` (back off
        per `Retry-After`). While img.pro cannot yet confirm whether a create
        was saved it returns `503 create_outcome_ambiguous`; retry the identical
        request after `Retry-After`, which never makes a duplicate. A key whose
        earlier create can no longer be replayed returns `409
        idempotency_recovery_conflict`: stop retrying and use a new key. Use a fresh globally unique key for every
        logical create. Idempotency state is retained 24h; retry only the identical
        request during that window. After 24h, replay and duplicate prevention are
        not guaranteed, so do not retry the old operation or repurpose its key. A completed URL
        import replays without another fetch during that window; if retained cache
        state is unavailable, URL recovery may require the source to remain fetchable.
        `metadata` is part of the
        hashed body: changing a custom field on a retry is a different body;
        metadata is attribution, not a dedup key, so `Idempotency-Key` is the
        only retry-safety channel (there is no external_id upsert).

        An App-wide key uses App storage by default; add X-Img-User only to
        select a connected user. See /api/app.
      operationId: createImage
      parameters:
        - name: Idempotency-Key
          in: header
          required: false
          schema:
            type: string
            maxLength: 255
          description: |
            Globally unique retry-safety key for one logical create (maximum
            255 UTF-8 bytes). Idempotency state is retained 24h; during that
            window the same key + body replays or recovers the original, a
            different body returns 409 conflict, and an original still in
            flight returns 409 in-progress. After 24h, replay and duplicate
            prevention are not guaranteed, so do not retry or repurpose the
            key. After retained cache loss, a URL import may require its source
            to remain fetchable.
        - $ref: '#/components/parameters/XImgUser'
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file:
                  type: string
                  format: binary
                ttl:
                  type: string
                  description: Auto-delete after duration (e.g., `24h`, `7d`). Omit for no expiry, or send `never`, an empty multipart field, or JSON null.
                caption:
                  type: string
                  maxLength: 5000
                  description: Free-text caption / description for the image. Over-length values are rejected with 422.
                published_at:
                  type: string
                  description: |
                    Publish date: a unix timestamp (seconds) or ISO-8601 date
                    string (`2024-06-01`). Backdate to sort under the photo's
                    date (a 2024 photo uploaded in 2026 sorts under 2024). Omit
                    to default to the upload time.
                metadata:
                  type: string
                  description: |
                    Custom attribution fields as a JSON-encoded object, e.g.
                    `{"author":"Jane","license":"cc-by-4.0"}`, the same nested
                    shape the Image response returns. This is the only channel for
                    custom fields (a multipart form field can't hold an object, so
                    it's JSON-encoded here); a bare unknown form field is rejected
                    with 422.
                labels:
                  type: string
                  description: |
                    Selector labels as a JSON-encoded object, e.g.
                    `{"state":"pending","kind":"generated"}`, the queryable sibling
                    of `metadata` you can later filter a list on
                    (`GET /v1/images?label[k]=v`). Bounds: ≤ 20 keys, key
                    `^[a-z0-9_.-]{1,64}$`, value ≤ 128 chars (no commas, no surrounding whitespace).
              additionalProperties: false
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url:
                  type: string
                  format: uri
                ttl:
                  type: [string, integer, 'null']
                  description: Auto-delete after duration (e.g., `24h`, `7d`). Omit for no expiry, or send `never`, an empty multipart field, or JSON null.
                caption:
                  type: string
                  maxLength: 5000
                  description: Free-text caption / description for the image. Over-length values are rejected with 422.
                published_at:
                  type: string
                  description: |
                    Publish date: a unix timestamp (seconds) or ISO-8601 date
                    string (`2024-06-01`). Omit to default to the upload time.
                metadata:
                  type: object
                  additionalProperties:
                    type: string
                  description: |
                    Custom attribution fields as a nested string→string map,
                    identical to what the Image response returns. This is the only
                    channel for custom fields; a bare unknown top-level field is
                    rejected with 422.
                labels:
                  type: object
                  additionalProperties:
                    type: string
                  description: |
                    Selector labels as a nested string→string map, the queryable
                    sibling of `metadata` you can later filter a list on
                    (`GET /v1/images?label[k]=v`). Bounds: ≤ 20 keys, key
                    `^[a-z0-9_.-]{1,64}$`, value ≤ 128 chars (no commas, no surrounding whitespace).
              additionalProperties: false
      responses:
        '201':
          description: |
            Image created. Authenticated creates return the usage
            headers below.
          headers:
            X-Limits-Enforced:
              $ref: '#/components/headers/X-Limits-Enforced'
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Image'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: |
            Insufficient key permissions (forbidden), an App-wide key on a
            paused or blocked App (app_suspended), an App-storage key's write to a
            blocked App (app_blocked), an unavailable connected user
            (user_forbidden), or the App at its plan's images limit,
            5,000 on Free and 50,000 on Pro (quota_exceeded,
            `quota_error`), which stores nothing and carries
            `X-Limits-Enforced: true`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                free:
                  summary: An App on Free at its images limit
                  value:
                    error:
                      type: quota_error
                      code: quota_exceeded
                      message: "This App is at the Free limit of 5,000 images, so it accepts no new uploads. Upgrade it to Pro in Billing: https://img.pro/billing"
                pro:
                  summary: An App on Pro at its images limit
                  value:
                    error:
                      type: quota_error
                      code: quota_exceeded
                      message: "This App is at the Pro limit of 50,000 images, so it accepts no new uploads. Upgrade it to Unlimited in Billing: https://img.pro/billing"
        '409':
          $ref: '#/components/responses/CreateConflict'
        '422':
          $ref: '#/components/responses/ValidationError'
        '502':
          description: Fetch failed (URL import)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  type: processing_error
                  code: fetch_failed
                  message: "Could not fetch the URL"
        '504':
          description: URL import timed out before the source body completed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  type: processing_error
                  code: fetch_failed
                  message: "URL fetch timeout"
        '503':
          description: |
            img.pro could not check the key's App in time, or cannot confirm yet
            whether the create was saved. Retry the identical request after
            Retry-After.
          headers:
            Retry-After:
              description: Seconds to wait before retrying.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                appContextUnavailable:
                  summary: The key's App could not be checked in time
                  value:
                    error:
                      type: api_error
                      code: app_context_unavailable
                      message: "img.pro couldn't check this key's App in time. Retry after Retry-After."
                      action: { type: wait, retry_after: 2 }
                createOutcomeAmbiguous:
                  summary: img.pro cannot confirm yet whether the create was saved
                  value:
                    error:
                      type: api_error
                      code: create_outcome_ambiguous
                      message: "img.pro is still confirming whether this upload was saved. Retry the same request after Retry-After."
                      action: { type: wait, retry_after: 2 }

    get:
      tags: [Images]
      summary: List Images
      description: |
        List images, ordered by `published_at` newest-first (backdate or
        re-stamp an image's `published_at` to re-sort it). Cursor-based
        pagination: follow `pagination.next_url` or pass the previous
        page's `next_cursor`. Lists carry only images with
        `status: ready`; images still processing, blocked or failed are left out.

        An App-wide key uses App storage by default; add X-Img-User only to
        select a connected user. See /api/app.
      operationId: listImages
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/XImgUser'
        - name: ids
          in: query
          schema:
            type: string
          description: Comma-separated IDs to fetch specific items. Cannot be combined with `label[...]` filters.
        - name: label
          in: query
          style: deepObject
          explode: true
          schema:
            type: object
            additionalProperties:
              type: string
          description: |
            Filter by labels: `?label[state]=pending`. A CSV or repeated key is
            `IN` (`?label[state]=pending,liked`); distinct keys `AND`
            (`?label[state]=pending&label[kind]=generated`). A `!` prefix is
            does-not-exist (Kubernetes `!key`): `?label[!state]` matches media with
            NO `state` label, the only way to reach images your App never labeled;
            it takes no value. Equality + IN + does-not-exist in v1; at most
            50 value alternatives across all keys combined and
            20 keys total. Filtering a value on a key you never set returns
            an empty page (not an error). Cannot be combined with `ids`. Keep the same
            filter across every page of a walk: the cursor is a position in that
            filtered ordering.
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
        - name: cursor
          in: query
          schema:
            type: string
          description: Opaque pagination cursor from the previous page's `next_cursor`
      responses:
        '200':
          description: Image list
          headers:
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageListResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

  /v1/images/{id}:
    get:
      tags: [Images]
      summary: Get Image
      description: |
        Get a single image from the storage your key reaches: an App-wide key
        reads App storage, or a connected user's storage with X-Img-User. A
        key is required; the image file itself loads from its `url` without
        one. An id outside that storage, another App's included, answers
        `404` exactly as an id that does not exist. A blocked image answers
        `403 media_blocked` with the coarse reason; a failed image answers
        `422 media_failed` with a human-readable explanation.
      operationId: getImage
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/MediaId'
        - $ref: '#/components/parameters/XImgUser'
      responses:
        '200':
          description: Image details
          headers:
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Image'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Image blocked by moderation (code media_blocked), insufficient key permissions (forbidden), an App-wide key on a paused or blocked App (app_suspended), or an unavailable connected user (user_forbidden)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  type: permission_error
                  code: media_blocked
                  message: "This image was blocked (content_policy) and is no longer available."
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          description: Image processing failed permanently (code media_failed)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  type: processing_error
                  code: media_failed
                  message: "This HEIC image could not be read."
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

    patch:
      tags: [Images]
      summary: Update Image
      operationId: updateImage
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/MediaId'
        - $ref: '#/components/parameters/XImgUser'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/MediaUpdate'
      responses:
        '200':
          description: Updated
          headers:
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Image'
        '403':
          description: Image is moderation-locked and cannot be modified (code media_locked), insufficient key permissions (forbidden), an App-storage key's write to a blocked App (app_blocked), an App-wide key on a paused or blocked App (app_suspended), or an unavailable connected user (user_forbidden)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: A supplied if_labels precondition no longer matches (code state_conflict)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: Invalid update input (code validation_error) or a permanently failed image (code media_failed)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

    delete:
      tags: [Images]
      summary: Delete Image
      operationId: deleteImage
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/MediaId'
        - $ref: '#/components/parameters/XImgUser'
      responses:
        '200':
          description: Deleted. A tombstone confirms the deletion.
          content:
            application/json:
              schema:
                type: object
                required: [id, object, deleted]
                properties:
                  id:
                    type: string
                  object:
                    type: string
                    enum: [image]
                  deleted:
                    type: boolean
          headers:
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

  /v1/images/batch:
    patch:
      tags: [Images]
      summary: Batch Update
      description: |
        Update up to 100 media items by ID. More than 100 ids returns 422
        validation_error. 200 when all succeed; 207 when some items fail (each
        failure appears in the `errors` array).
      operationId: batchUpdateImages
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/XImgUser'
      requestBody:
        content:
          application/json:
            schema:
              type: object
              required: [ids]
              properties:
                ids:
                  type: array
                  items:
                    type: string
                  maxItems: 100
                caption:
                  type: string
                  maxLength: 5000
                ttl:
                  type: string
                  description: Apply this TTL to every item in the batch (e.g., `7d`). `null` makes them permanent.
                published_at:
                  type: string
                  description: Publish date (unix seconds or ISO-8601, e.g. `2024-06-01`) applied to every item.
                metadata:
                  type: object
                  additionalProperties:
                    type: [string, 'null']
                  description: |
                    Attribution fields (nested) merged into EVERY item's existing
                    metadata. A `null` value deletes that key on each item. This is
                    the only channel for custom fields; a bare unknown top-level
                    field is rejected with 422.
                labels:
                  type: object
                  additionalProperties:
                    type: [string, 'null']
                  description: |
                    Selector labels (nested) merged into EVERY item's existing
                    labels. A `null` value deletes that key on each item. Same
                    bounds as the single-item PATCH.
                if_labels:
                  type: object
                  additionalProperties:
                    type: string
                  minProperties: 1
                  description: |
                    Atomic precondition applied to every item: all supplied
                    labels must still equal these values when each update
                    commits. A mismatch is reported per item as state_conflict.
              additionalProperties: false
      responses:
        '200':
          description: Updated
          headers:
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchResult'
        '207':
          description: Some items were skipped; each lifecycle, permission, not-found, or precondition failure appears in errors
          headers:
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchResult'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

    delete:
      tags: [Images]
      summary: Batch Delete
      description: |
        Delete up to 100 media items by ID. More than 100 ids returns 422
        validation_error.

        `{"ids": ["a", "b", "c"]}`
      operationId: batchDeleteImages
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/XImgUser'
      requestBody:
        content:
          application/json:
            schema:
              type: object
              required: [ids]
              properties:
                ids:
                  type: array
                  items:
                    type: string
                  maxItems: 100
      responses:
        '200':
          description: Deleted
          headers:
            X-Monthly-Uploads-Used:
              $ref: '#/components/headers/X-Monthly-Uploads-Used'
            X-Monthly-Uploads-Limit:
              $ref: '#/components/headers/X-Monthly-Uploads-Limit'
            X-Monthly-Uploads-Remaining:
              $ref: '#/components/headers/X-Monthly-Uploads-Remaining'
            X-Storage-Used:
              $ref: '#/components/headers/X-Storage-Used'
            X-Storage-Limit:
              $ref: '#/components/headers/X-Storage-Limit'
            X-Storage-Remaining:
              $ref: '#/components/headers/X-Storage-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchResult'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

  /v1/auth/exchange:
    post:
      tags: [App]
      summary: Exchange Connect Code
      description: |
        Exchange a one-time `code` from img.pro sign-in (the `/connect` flow) for
        an `auth_context` describing the user that just connected.
        Backend-mediated: the App's server calls this with an App-wide key that has read permission;
        no token is ever handed to a browser. See /api/app for the full flow.
      operationId: exchangeConnectCode
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              properties:
                code:
                  type: string
                  description: One-time code that `/connect` returns to your callback (`?code=`).
      responses:
        '200':
          description: The user who just connected
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AuthContext'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          description: Invalid or expired code (code invalid_code)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  type: invalid_request_error
                  code: invalid_code
                  message: "Invalid or expired authorization code"
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

  /v1/billing/status:
    get:
      tags: [Billing]
      summary: Check what a user has
      description: |
        What one user has in the plans your App sells. Use an
        App-wide key with X-Img-User, or that user's own key; the key
        selects your App. Give the user what `access.plan_key` names; it
        is null while `access.status` is `inactive`. Offer a trial only when
        `trial_eligible` is true and the price has `trial_days`. Read it
        again when the user comes back from `billing_url`: the return
        itself grants nothing. While img.pro confirms a renewal it answers
        `503 server_error` with `Retry-After` and a wait action: keep the
        access you last read for this user, and retry.

        Changed September 29, 2026: this endpoint no longer answers with an img.pro
        plan and usage, with or without X-Img-User. With a user, `plan`,
        `usage`, `limits_enforced` and `available_plans` are gone: read
        `access` and `subscription`. Your App's img.pro plan and usage are
        at `GET /v1/usage`. Called without a user, it answers 403 and says
        so.
      operationId: getBillingStatus
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/BillingPerson'
      responses:
        '200':
          description: What this user has in your App's plans
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BillingStatus'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: |
            A key without read permission (forbidden); a read without a user,
            the meaning this endpoint had before September 29, 2026, from an App-wide
            key without X-Img-User or a key for App storage only (forbidden);
            an App-wide key on a paused or blocked App (app_suspended); or a
            user who is not connected to your App (user_forbidden). The
            message says which, and what to send instead.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  type: permission_error
                  code: forbidden
                  message: "GET /v1/billing/status changed on September 29, 2026: it now reads one user's subscription to your App's plans, so send X-Img-User with their id. Your App's img.pro plan and usage are at GET /v1/usage."
        '422':
          $ref: '#/components/responses/ValidationError'
        '503':
          description: |
            img.pro could not check the key's App in time (app_context_unavailable),
            or is still confirming this user's renewal (server_error). Both
            carry `Retry-After` and a wait action. During a renewal, keep the
            access you last read for this user until the retry answers.
          headers:
            Retry-After:
              description: Seconds to wait before retrying.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                appContextUnavailable:
                  value:
                    error:
                      type: api_error
                      code: app_context_unavailable
                      message: "img.pro couldn't check this key's App in time. Retry after Retry-After."
                      action:
                        type: wait
                        retry_after: 2
                billingConfirmationPending:
                  value:
                    error:
                      type: api_error
                      code: server_error
                      message: "img.pro is still confirming this user's renewal. Keep the access you last read, and retry after Retry-After."
                      action:
                        type: wait
                        retry_after: 30

  /v1/billing/plans:
    get:
      tags: [Billing]
      summary: List your plans
      description: |
        The plans your App sells, each with every price of it that is on
        sale, in the Display order you set in Pricing: by `display_order`,
        then name, then id, the order the hosted billing card shows your users.
        Use an App-wide key with read permission; it selects your App, so the
        request names no App and no user. Amounts are in the currency's
        smallest unit (cents for `usd`). When `purchasing_enabled` is false,
        hide your buy buttons: users who already subscribe can still manage
        their plan. Only plans with a price on sale appear. It returns the
        standard cursor-paginated list: follow `pagination.next_url` while
        `has_more` is true.
      operationId: listBillingPlans
      security:
        - bearerAuth: []
      parameters:
        - in: query
          name: limit
          description: Plans per page, from 1 to 100. Any other value is `422 validation_error`.
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
        - in: query
          name: cursor
          description: The previous page's `pagination.next_cursor`, for your App only. A cursor this list did not give you is `422 validation_error`; start again without one.
          schema:
            type: string
      responses:
        '200':
          description: Your App's plans with a price on sale, each with its prices on sale
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BillingPlanList'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          description: |
            A `limit` outside 1 to 100, a cursor this list did not give you,
            `limit` or `cursor` sent twice, or a parameter that names an App
            (your key already selects it). `details` names each parameter.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error:
                  type: invalid_request_error
                  code: validation_error
                  message: "Validation failed"
                  details:
                    cursor: ["This cursor is not valid for this list. Start again without a cursor."]
        '503':
          $ref: '#/components/responses/AppContextUnavailable'

  /{prefix}/{filename}:
    get:
      tags: [Transforms]
      servers:
        - url: https://src.img.pro
          description: Image CDN
      summary: Transform an Image
      description: |
        The image CDN. Every API response's `url` points here; this operation
        is that URL. Append query parameters to resize, convert, crop,
        color-correct, or remove the background with no extra API call. Each
        distinct URL is cached independently at the edge worldwide.

        No authentication: the `url` is a public capability link. Parameter
        order doesn't matter. Unsupported values may be ignored or fall back
        to the default rendition. New transformations of an image may be
        limited to prevent abuse (429); named sizes always work.
        A brief failure of img.pro's storage or image processor can return a retryable 503.
        With no valid transform parameter (`download=1` is not one) it serves
        the original as a high-quality copy re-encoded in the same format,
        the same for everyone and never as uploaded: Public images carry pixels only: no public image carries location, camera or device details, capture time, edit history, embedded previews or provenance manifests. Their color is converted to sRGB, and an original's rotation is applied to its pixels. Downloaded with download=1, an original keeps the name it was uploaded with, which may record when it was taken.
        Full guide with examples: /api/transforms.
      operationId: transformImage
      security: []
      parameters:
        - name: prefix
          in: path
          required: true
          description: The short segment before the image id in `url` (e.g. `4j2`). Copy `url` as the API returns it; never build it.
          schema: { type: string }
        - name: filename
          in: path
          required: true
          description: The image id plus an extension, e.g. `abc12345.jpg`, as `url` has it. The extension is `jpg`, `jpeg`, `png`, `gif`, `webp` or `avif`, in any case; any other, `.heic` and `.heif` included, answers 404. The `format` query param overrides the extension.
          schema: { type: string }
        - name: size
          in: query
          description: Named size preset that supplies the base recipe; it can be combined with the parameters below, and explicit query parameters override matching preset fields. `s`/`m`/`l` constrain the short side to 320/640/1080px (aspect preserved); `social` is a fixed 1200×630 OpenGraph card.
          schema: { type: string, enum: [s, m, l, social] }
        - name: format
          in: query
          description: Output format. Overrides the extension in the path. `webp` is the best size/quality balance; `png` is lossless with transparency.
          schema: { type: string, enum: [jpg, png, webp, avif, gif] }
        - name: w
          in: query
          description: Target width in pixels. Set `w` or `h` alone to scale proportionally, or both with `fit`.
          schema: { type: integer, minimum: 1, maximum: 4096 }
        - name: h
          in: query
          description: Target height in pixels.
          schema: { type: integer, minimum: 1, maximum: 4096 }
        - name: fit
          in: query
          description: How the image fills `w`×`h`. `cover`/`crop` fill and trim; `contain`/`pad` letterbox; `scale-down` never enlarges.
          schema: { type: string, enum: [scale-down, contain, cover, crop, pad, squeeze], default: scale-down }
        - name: gravity
          in: query
          description: Which part to keep when cropping. `face` centers on detected faces.
          schema: { type: string, enum: [auto, face, left, right, top, bottom], default: auto }
        - name: zoom
          in: query
          description: Crop tightness around `gravity=face` (0 = most context, 1 = tight).
          schema: { type: number, minimum: 0, maximum: 1 }
        - name: q
          in: query
          description: Output quality for lossy formats (JPEG/WebP/AVIF). A number 1–100, or a named level (`high`≈90, `medium-high`≈75, `medium-low`≈60, `low`≈45). No effect on PNG (always lossless).
          schema: { type: string }
        - name: brightness
          in: query
          description: Multiplier centered at 1 (0 = black, 2 = twice as bright). Useful range ~0.5–2.
          schema: { type: number, minimum: 0, maximum: 10, default: 1 }
        - name: contrast
          in: query
          description: Multiplier centered at 1 (>1 = punchier). Useful range ~0.7–2.
          schema: { type: number, minimum: 0, maximum: 10, default: 1 }
        - name: gamma
          in: query
          description: Multiplier (<1 lightens midtones, >1 darkens; 0 and 1 are no-ops). Useful range ~0.5–2.5.
          schema: { type: number, minimum: 0, maximum: 10, default: 1 }
        - name: saturation
          in: query
          description: Multiplier centered at 1 (0 = grayscale, >1 = vivid). Useful range ~0.5–2.
          schema: { type: number, minimum: 0, maximum: 10, default: 1 }
        - name: blur
          in: query
          description: Gaussian blur radius in pixels.
          schema: { type: integer, minimum: 0, maximum: 250, default: 0 }
        - name: sharp
          in: query
          description: Unsharp-mask intensity (1–3 subtle, 4–6 noticeable, 7+ aggressive).
          schema: { type: number, minimum: 0, maximum: 10, default: 0 }
        - name: rotate
          in: query
          description: Clockwise rotation in degrees.
          schema: { type: integer, enum: [90, 180, 270] }
        - name: flip
          in: query
          description: Mirror horizontally, vertically, or both.
          schema: { type: string, enum: [h, v, hv] }
        - name: trim
          in: query
          description: Auto-crop a uniform border color around the image.
          schema: { type: string, enum: [border] }
        - name: segment
          in: query
          description: Remove the background (edge segmentation model). Pair with `format=png` to keep transparency.
          schema: { type: string, enum: [foreground] }
        - name: background
          in: query
          description: Fill color for transparent areas, a CSS named color, hex (URL-encode `#` as `%23`), or `rgb()`/`rgba()`. After `segment=foreground` it swaps the background; on its own it fills transparent pixels. When omitted, alpha-capable formats stay transparent and others fill white (no img.pro-enforced default).
          schema: { type: string }
        - name: download
          in: query
          description: With `1`, serves the same image as an attachment, so a browser saves it. The original, at a URL with no valid transform parameter, is named as it was uploaded; a transformed image, a converted format included, is named `{id}.{ext}`, the extension of the format served. Not a transform on its own.
          schema: { type: string, enum: ['1'] }
      responses:
        '200':
          description: The image bytes (content type follows the requested format). At a URL with no valid transform parameter, the original re-encoded in its own format without its embedded metadata (lossless for PNG, though an animated PNG becomes a still image; animation kept for GIF and WebP), so its length is not the image's `bytes`, the same for every request. Otherwise the transformed image.
          content:
            image/*:
              schema:
                type: string
                format: binary
        '404':
          description: |
            No image at this URL: an unknown id or prefix, a deleted or
            expired image, or an extension other than jpg, jpeg, png, gif,
            webp or avif (`.heic` and `.heif` included), whether or not
            the image exists. Every stored image loads here for anyone
            holding its URL.
        '422':
          description: An image that cannot be served without its metadata is not served at all (an original over 20 MB in storage, an original that cannot be decoded, or a re-encoded or transformed image that would carry metadata or could not be checked for it). Not retryable as it is.
        '429':
          description: |
            New transformations of this image are limited right now, to prevent
            abuse. Its named sizes, its original and the versions already made
            keep working. Use a named size, or write to support@img.pro. The
            body says so in one sentence.
        '503':
          description: A brief failure of img.pro's storage or image processor. Retry the identical URL after the advertised delay.
          headers:
            Retry-After:
              description: Retry delay in seconds for application-generated transient failures.
              schema: { type: integer, example: 2 }

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        API key whose reach is App-wide or App storage only (scope `app` or
        `bucket`), with read/write permissions. Keep it on the backend.
        App-wide keys select App storage by default; X-Img-User selects a
        connected user's storage. A key that is not App-wide rejects
        X-Img-User. App status gates App-wide keys; App-storage keys keep
        their own reach and permission and lifecycle checks.

  headers:
    X-Limits-Enforced:
      description: |
        Whether the App's plan limits apply: true on Free (5,000 images
        and 50 users per App) and Pro (50,000 images and 500 users
        per App), false on Unlimited. Sent on creates and on
        GET /v1/usage, the responses that read the App's plan.
      schema:
        type: boolean
    X-Monthly-Uploads-Used:
      description: Uploads used this month
      schema:
        type: integer
    X-Monthly-Uploads-Limit:
      description: Monthly upload limit (informational; it never refuses an upload)
      schema:
        type: integer
    X-Monthly-Uploads-Remaining:
      description: Uploads left against that limit (informational)
      schema:
        type: integer
    X-Storage-Used:
      description: Bytes stored
      schema:
        type: integer
    X-Storage-Limit:
      description: Storage limit in bytes (informational; it never refuses an upload)
      schema:
        type: integer
    X-Storage-Remaining:
      description: Bytes left against that limit (informational)
      schema:
        type: integer

  parameters:
    MediaId:
      name: id
      in: path
      required: true
      schema:
        type: string
    XImgUser:
      name: X-Img-User
      in: header
      required: false
      schema:
        type: string
      description: |
        Optional for App-wide keys. Omit for the App storage; include the
        opaque user id returned by img.pro sign-in to select that connected
        user's storage within the App. Blank/malformed values return 422;
        unavailable or unconnected users return 403 user_forbidden. A rejected
        selector never falls back. A key that is not App-wide rejects this
        header (422).
    BillingPerson:
      name: X-Img-User
      in: header
      required: false
      schema:
        type: string
      description: |
        The user to read. Required with an App-wide key; leave it
        out when you use that user's own key, which already names them.
        Blank or malformed values return 422; a user who is not connected
        to your App returns 403 user_forbidden.

  schemas:
    UsageResponse:
      type: object
      required: [object, monthly, totals, plan, limits_enforced, limits]
      description: |
        The selected storage's usage, and the App's plan with its limits.
        `monthly` and `totals` carry monthly upload and storage limit
        values, which are informational.
      properties:
        limits_enforced:
          type: boolean
          description: True on Free and Pro, whose limits refuse new uploads and first sign-ins; false on Unlimited.
        object:
          type: string
          enum: [usage]
          description: Always `"usage"`.
        monthly:
          type: object
          properties:
            uploads:
              type: integer
            uploads_limit:
              type: integer
            uploads_remaining:
              type: integer
            resets_at:
              type: string
              format: date-time
              description: ISO-8601 UTC timestamp of the next monthly usage counter reset
        totals:
          type: object
          properties:
            images_stored:
              type: integer
            storage_used_bytes:
              type: integer
            storage_limit_bytes:
              type: integer
            storage_remaining_bytes:
              type: integer
        plan:
          type: string
          enum: [free, pro, unlimited]
          description: |
            The App's img.pro plan: `free`, `pro` or `unlimited`. Treat a
            value you don't know as a safe default and read `limits`.
        limits:
          type: object
          required: [images, users]
          description: |
            The whole App against its plan's limits: its storage and every
            connected user's. `limit` is null on Unlimited. `used` is null for a
            key a connected user issued for their own storage.
          properties:
            images:
              $ref: '#/components/schemas/UsageLimit'
            users:
              $ref: '#/components/schemas/UsageLimit'

    UsageLimit:
      type: object
      required: [used, limit]
      properties:
        used:
          type: [integer, 'null']
          description: Stored images, or connected users, across the whole App.
        limit:
          type: [integer, 'null']
          description: The plan's limit (Free 5,000 images and 50 users, Pro 50,000 images and 500 users), or null on Unlimited.

    AuthContext:
      type: object
      required: [object, app, user]
      description: The user connected by an exchanged `/connect` code.
      properties:
        object:
          type: string
          enum: [auth_context]
          description: Always `"auth_context"`.
        app:
          type: object
          required: [id, object, name]
          properties:
            id:
              type: string
            object:
              type: string
              enum: [app]
            name:
              type: string
        user:
          type: object
          required: [id, object, email, verified]
          properties:
            id:
              type: string
            object:
              type: string
              enum: [user]
            email:
              type: string
            verified:
              type: boolean

    BillingApp:
      type: object
      required: [id, object, name]
      properties:
        id:
          type: string
          description: Opaque public App id.
        object:
          type: string
          const: app
        name:
          type: string
    BillingPrice:
      type: object
      required: [id, object, amount, currency, interval, trial_days]
      properties:
        id:
          type: string
          description: Opaque img.pro Price id. Pass it to the hosted card as price_id; for a price on sale, a user with no current plan goes straight to Stripe Checkout once signed in, otherwise it is the plan chosen on the card.
        object:
          type: string
          const: price
        amount:
          type: integer
          minimum: 1
          description: The price per interval in the currency's smallest unit (cents for `usd`).
        currency:
          type: string
          pattern: '^[a-z]{3}$'
        interval:
          type: string
          enum: [month, year]
        trial_days:
          type: integer
          minimum: 0
          description: Free days before the first charge, or 0. A user gets one trial per App.
    BillingPlan:
      type: object
      required: [id, object, key, name, description, benefits, display_order, prices]
      properties:
        id:
          type: string
          description: Opaque img.pro Plan id.
        object:
          type: string
          const: plan
        key:
          type: string
          description: The plan key you chose. Your App reads it to decide what a subscriber gets; it never changes.
        name:
          type: string
        description:
          type: string
        benefits:
          type: array
          items:
            type: string
        display_order:
          type: integer
          minimum: 0
          description: The Display order you set in Pricing. Lower numbers come first, then name; the list comes in this order, as on the hosted billing card.
        prices:
          type: array
          minItems: 1
          description: Every Price of this Plan that is on sale, ordered by interval and id.
          items:
            $ref: '#/components/schemas/BillingPrice'
    BillingPlanList:
      type: object
      required: [object, app, purchasing_enabled, data, pagination]
      properties:
        object:
          type: string
          const: list
        app:
          $ref: '#/components/schemas/BillingApp'
        purchasing_enabled:
          type: boolean
          description: True only while new subscriptions are open in Pricing and a plan is on sale, and false while your App is paused or blocked.
        data:
          type: array
          items:
            $ref: '#/components/schemas/BillingPlan'
        pagination:
          type: object
          required: [has_more, next_cursor, next_url]
          properties:
            has_more:
              type: boolean
            next_cursor:
              type: [string, 'null']
              description: Opaque App-bound cursor, null at the end.
            next_url:
              type: [string, 'null']
              format: uri
              description: Absolute next-page URL, null at the end.
      example:
        object: list
        app: { id: a8o46yrk, object: app, name: Example App }
        purchasing_enabled: true
        data:
          - id: opaque-plan-id
            object: plan
            key: personal
            name: Personal
            description: For personal projects
            benefits: [One board]
            display_order: 1
            prices:
              - { id: opaque-monthly-price-id, object: price, amount: 1000, currency: usd, interval: month, trial_days: 7 }
              - { id: opaque-yearly-price-id, object: price, amount: 10000, currency: usd, interval: year, trial_days: 7 }
        pagination: { has_more: false, next_cursor: null, next_url: null }
    BillingSubscription:
      type: object
      required: [id, object, plan_key, price_id, status, trial_end, current_period_end, cancel_at_period_end, cancel_at, pending_plan_key, pending_effective_at]
      properties:
        id:
          type: string
          description: Opaque img.pro Subscription id.
        object:
          type: string
          const: subscription
        plan_key:
          type: string
          description: The key of the plan this subscription is for. What the user has now is `access.plan_key`.
        price_id:
          type: string
          description: Opaque img.pro Price id. It stays the same after the price is taken off sale or archived.
        status:
          type: string
          enum: [incomplete, incomplete_expired, trialing, active, past_due, canceled, unpaid, paused, unknown]
          description: The subscription's state, for information. A state img.pro does not recognize reads unknown. Read access to decide what a user gets.
        trial_end:
          type: [string, 'null']
          format: date-time
        current_period_end:
          type: [string, 'null']
          format: date-time
        cancel_at_period_end:
          type: boolean
        cancel_at:
          type: [string, 'null']
          format: date-time
          description: Explicit cancellation deadline, independently of cancel_at_period_end.
        pending_plan_key:
          type: [string, 'null']
          description: The plan a scheduled change moves to, or null.
        pending_effective_at:
          type: [string, 'null']
          format: date-time
          description: Scheduled change time; null for a pending upgrade awaiting payment.
    BillingStatus:
      type: object
      required: [object, app, purchasing_enabled, trial_eligible, has_subscribed, access, subscription, billing_url]
      description: One user's subscription to your App's plans. All dates are ISO 8601 UTC strings or null.
      properties:
        object:
          type: string
          const: billing_status
        app:
          $ref: '#/components/schemas/BillingApp'
        purchasing_enabled:
          type: boolean
          description: True only while new subscriptions are open in Pricing and a plan is on sale, and false while your App is paused or blocked. Users who already subscribe can always manage theirs.
        trial_eligible:
          type: boolean
          description: Whether this user can still start a trial. A user gets one trial per App, even after cancelling and reconnecting.
        has_subscribed:
          type: boolean
          description: True once the user has started a trial or paid for a plan in your App. Unfinished payments don't count.
        access:
          type: object
          required: [plan_key, status, expires_at]
          description: What the user has now. Decide what they get from this, never from `subscription.status`.
          properties:
            plan_key:
              type: [string, 'null']
              description: The key of the plan the user has now, or null while `status` is `inactive`.
            status:
              type: string
              enum: [inactive, trialing, active, grace]
              description: One of `inactive` (no plan), `trialing`, `active`, or `grace` (a payment failed and the few days of grace are still running).
            expires_at:
              type: [string, 'null']
              format: date-time
              description: When this access ends unless it renews, or null.
        subscription:
          anyOf:
            - $ref: '#/components/schemas/BillingSubscription'
            - type: 'null'
        billing_url:
          type: string
          format: uri
          description: Hosted App billing card. Append a registered exact redirect_uri, optional state and optional Price id as price_id. With a price on sale, a user with no current plan goes straight to Stripe Checkout once signed in; backing out returns to redirect_uri with state and without billing.
      example:
        object: billing_status
        app: { id: a8o46yrk, object: app, name: Example App }
        purchasing_enabled: true
        trial_eligible: false
        has_subscribed: true
        access: { plan_key: personal, status: active, expires_at: '2026-11-26T00:00:00.000Z' }
        subscription:
          id: opaque-subscription-id
          object: subscription
          plan_key: personal
          price_id: opaque-monthly-price-id
          status: active
          trial_end: null
          current_period_end: '2026-11-26T00:00:00.000Z'
          cancel_at_period_end: false
          cancel_at: null
          pending_plan_key: null
          pending_effective_at: null
        billing_url: https://img.pro/apps/billing?app=a8o46yrk

    ImageSize:
      type: object
      required: [url]
      properties:
        url:
          type: string
          format: uri
          description: Direct CDN URL for this named variant.
        width:
          type: integer
          description: Variant width in pixels (omitted when source dimensions are unavailable).
        height:
          type: integer
          description: Variant height in pixels (omitted when source dimensions are unavailable).

    Image:
      type: object
      required:
        - id
        - object
        - url
        - sizes
        - filename
        - format
        - status
        - width
        - height
        - bytes
        - published_at
        - expires_at
        - created_at
        - caption
        - metadata
        - labels
        - nsfw
      properties:
        id:
          type: string
          description: Media UID (e.g. `abc12345`).
        object:
          type: string
          enum: [image]
          description: Object type discriminator. Always `"image"`.
        url:
          type: string
          format: uri
          description: |
            The image itself: a direct, embeddable CDN URL (e.g.
            `https://src.img.pro/4j2/abc12345.jpg`). Always present. Append or
            change query params (format, w, h, q, …) to get variants on the fly;
            see /api/transforms.
        sizes:
          type: object
          description: |
            Responsive variants `small`, `medium` and `large`, aspect-preserved.
            For a social/OG card, use the `?size=social` transform (see
            /api/transforms).
          properties:
            small:
              $ref: '#/components/schemas/ImageSize'
            medium:
              $ref: '#/components/schemas/ImageSize'
            large:
              $ref: '#/components/schemas/ImageSize'
        filename:
          type: string
          description: |
            Original filename for download UX; falls back to
            `{id}.{format}` when the upload had none. Always present.
        format:
          type: string
          enum: [jpg, png, webp, avif, gif]
          description: |
            OUTPUT format, normalized: a stored HEIC serves as `jpg`, never
            `heic`. Useful for filenames or MIME-type guesses without an
            extra HEAD request.
        width:
          type: [integer, 'null']
          description: Source width in pixels. `null` only for some older images whose dimensions were never recorded. Always present.
        height:
          type: [integer, 'null']
          description: Source height in pixels. `null` only for some older images whose dimensions were never recorded. Always present.
        bytes:
          type: [integer, 'null']
          description: Stored file size in bytes. `null` only when the byte size is unavailable. Always present.
        status:
          type: string
          enum: [ready]
          description: |
            Every Image object is complete and servable. Creates return
            `ready` or fail in the request; images still processing, blocked or
            failed are never returned as Image objects.
        published_at:
          type: string
          format: date-time
          description: |
            Publish/display timestamp, ISO-8601 UTC (e.g. `2024-01-01T00:00:00Z`).
            Never `null`: defaults to the upload time when omitted. Drives list
            ordering: `GET /v1/images` sorts by it newest-first, so backdating
            or re-stamping re-sorts the item. Set on create/PATCH via the
            `published_at` input (a unix timestamp OR ISO-8601 date; inputs
            are lenient, output is always ISO-8601 UTC).
        expires_at:
          type: [string, 'null']
          format: date-time
          description: Auto-delete timestamp, ISO-8601 UTC. `null` = permanent. Always present.
        created_at:
          type: string
          format: date-time
          description: Upload timestamp, ISO-8601 UTC (e.g. `2024-01-01T00:00:00Z`). Always present.
        caption:
          type: [string, 'null']
          description: User-editable caption / description. `null` when unset. Always present.
        metadata:
          type: object
          additionalProperties: true
          description: |
            Open string→string map of your fields (author, license, source_url,
            tool, title, …), NESTED, so it can never shadow a core
            field. Always present; may be `{}`. Limits: ≤ 50 keys, key ≤ 64
            chars, value ≤ 1024 chars (exceeding any → 422 validation_error).
        labels:
          type: object
          additionalProperties:
            type: string
          description: |
            Bounded selector map, the QUERYABLE sibling of `metadata`. A small
            string→string map you filter a list on (`GET /v1/images?label[k]=v`,
            equality + IN). Always present; may be `{}`. Limits: ≤ 20 keys, key
            `^[a-z0-9_.-]{1,64}$`, value ≤ 128 chars, no commas or
            surrounding whitespace (exceeding any → 422 validation_error). Written
            nested with merge / null-clear, exactly like `metadata`.
        nsfw:
          type: boolean
          description: Flagged as NSFW by the moderation pipeline (read-only). Always present; `true` when flagged, else `false`.

    MediaUpdate:
      type: object
      description: |
        PATCH accepts `caption`, `ttl`, `published_at`, your
        attribution `metadata`, and your selector `labels`. Optional
        `if_labels` makes the write conditional on current selector values. An
        omitted field is left unchanged. Custom fields are set ONLY through the nested `metadata`
        object; selectors ONLY through the nested `labels` object, both
        identical to the Image response. A `null` value inside either deletes that
        key. An unknown top-level field is rejected with 422, including
        `tool`, `defaults`, `filename`, and `nsfw`. Existing saved
        transform recipes are preserved; your own `tool` attribution belongs
        inside `metadata`.
        (A literal whole-object GET→PATCH round-trip is NOT tolerated: `filename`
        and `nsfw` are always-present read-only response fields but are 422-rejected
        on write, so strip them first. The other read-only response fields
        (`id`, `object`, `url`, `sizes`, …) are ignored.)
      properties:
        caption:
          type: string
          maxLength: 5000
          description: Free-text caption / description. Send `null` or `""` to clear. Over-length values are rejected with 422.
        ttl:
          type: string
          description: Auto-delete after duration (e.g., `24h`, `7d`). `null` makes the image permanent.
        published_at:
          type: string
          description: Publish date (unix seconds or ISO-8601, e.g. `2024-06-01`); updates `published_at`.
        metadata:
          type: object
          additionalProperties:
            type: [string, 'null']
          description: |
            Your attribution fields as a nested string→string map, the only
            channel for custom fields. A `null` value deletes that key; keys you
            don't mention are left unchanged. Limits: ≤ 50 keys,
            key ≤ 64 chars, value ≤ 1024 chars (exceeding any → 422).
        labels:
          type: object
          additionalProperties:
            type: [string, 'null']
          description: |
            Your selector labels as a nested string→string map, the queryable
            sibling of `metadata`. Merge + null-clear semantics are identical. A
            `null` value deletes that key. Limits: ≤ 20 keys, key
            `^[a-z0-9_.-]{1,64}$`, value ≤ 128 chars, no commas or
            surrounding whitespace (exceeding any → 422).
        if_labels:
          type: object
          additionalProperties:
            type: string
          minProperties: 1
          description: |
            Atomic compare-and-set guard. Every supplied label must still equal
            the given string when the PATCH commits; otherwise no fields change
            and the request returns 409 state_conflict. Uses the same key/value
            bounds as labels; null and empty values are rejected.
      additionalProperties: false

    ImageListResponse:
      type: object
      required: [object, data, pagination]
      properties:
        object:
          type: string
          enum: [list]
        data:
          type: array
          items:
            $ref: '#/components/schemas/Image'
        pagination:
          type: object
          required: [has_more, next_cursor, next_url]
          properties:
            has_more:
              type: boolean
            next_cursor:
              type: [string, 'null']
              description: 'Opaque cursor for the next page; null at end of list.'
            next_url:
              type: [string, 'null']
              description: 'Ready-to-fetch URL for the next page; null at end of list.'

    BatchResult:
      type: object
      required: [object, data, errors]
      description: |
        One envelope for batch update AND delete. `200` when every item
        succeeds, `207` on partial failure. Update → `data` holds the updated
        Image objects. Delete → `data` holds tombstones (idempotent: every
        requested id reports `deleted: true`, gone-now or already-gone alike,
        unlike a single DELETE of a missing id, which answers 404). Per-item
        `errors` use the same nested error object as every other error; empty
        when all succeed.
      properties:
        object:
          type: string
          enum: [batch_result]
        data:
          type: array
          items:
            oneOf:
              - $ref: '#/components/schemas/Image'
              - type: object
                required: [id, object, deleted]
                properties:
                  id:
                    type: string
                  object:
                    type: string
                    enum: [image]
                  deleted:
                    type: boolean
        errors:
          type: array
          description: Per-item failures (e.g. an item moderation-locked on update). Empty array when every item succeeds.
          items:
            type: object
            required: [id, error]
            properties:
              id:
                type: string
              error:
                type: object
                required: [type, code, message]
                properties:
                  type:
                    type: string
                  code:
                    type: string
                  message:
                    type: string

    Error:
      type: object
      required: [error]
      description: |
        Every error, top-level and per batch item, is one nested `error`
        object. Branch on `error.type` (coarse category) or switch on
        `error.code` (specific). Success responses never carry an error.
      properties:
        error:
          type: object
          required: [type, code, message]
          properties:
            type:
              type: string
              enum: [invalid_request_error, authentication_error, permission_error, rate_limit_error, quota_error, idempotency_error, processing_error, api_error]
              description: Coarse category. Branch on this.
            code:
              type: string
              description: Specific machine-readable code (frozen registry; additive-only).
            message:
              type: string
              description: Human-readable explanation.
            action:
              type: object
              description: |
                What to do next (optional). Errors only, never on success
                responses. `wait` is used for rate limits, a key's App that
                img.pro could not check in time, an idempotent create still in
                flight, a create img.pro cannot confirm yet, and a renewal it is
                still confirming on `GET /v1/billing/status`; honor
                `retry_after` and retry the same operation.
              properties:
                type:
                  type: string
                  enum: [wait]
                retry_after:
                  type: integer
                  description: Seconds to wait before retrying (type=wait; mirrors the Retry-After header)
            details:
              type: object
              additionalProperties:
                type: array
                items:
                  type: string
              description: Field-level error messages (validation only)

  responses:
    AppContextUnavailable:
      description: img.pro could not check the key's App in time. Retry after the indicated delay.
      headers:
        Retry-After:
          description: Seconds to wait before retrying the same operation.
          schema:
            type: integer
            example: 2
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              type: api_error
              code: app_context_unavailable
              message: "img.pro couldn't check this key's App in time. Retry after Retry-After."
              action:
                type: wait
                retry_after: 2

    ValidationError:
      description: Validation failed
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              type: invalid_request_error
              code: validation_error
              message: "Validation failed"
              details:
                ttl: ["TTL must be at least 5 minutes (300 seconds)"]

    CreateConflict:
      description: "Create conflict: an Idempotency-Key conflict, one still in progress or one that can no longer be replayed, or storage that is being deleted. Retry-After is present for the in-progress case."
      headers:
        Retry-After:
          description: Seconds to wait before retrying an idempotency_key_in_progress response.
          schema:
            type: integer
            minimum: 1
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            workspaceUnavailable:
              summary: The storage this create writes to is being deleted
              value:
                error:
                  type: invalid_request_error
                  code: workspace_unavailable
                  message: "The storage this request writes to is being deleted, so it takes no new images."
            idempotencyConflict:
              summary: Idempotency-Key reused with a different body
              value:
                error:
                  type: idempotency_error
                  code: idempotency_key_conflict
                  message: "Idempotency-Key was already used with a different request body"
            idempotencyInProgress:
              summary: Original request still in flight
              value:
                error:
                  type: idempotency_error
                  code: idempotency_key_in_progress
                  message: "A request with this Idempotency-Key is still being processed. Retry shortly."
                  action:
                    type: wait
                    retry_after: 2
            recoveryConflict:
              summary: The key's earlier create can no longer be replayed
              value:
                error:
                  type: idempotency_error
                  code: idempotency_recovery_conflict
                  message: "This Idempotency-Key belongs to an earlier upload that can no longer be replayed. Use a new key for new work."

    NotFound:
      description: Not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              type: invalid_request_error
              code: not_found
              message: "Media not found"

    Forbidden:
      description: Insufficient key permissions (forbidden), an App-wide key on a paused or blocked App (app_suspended), an App-storage key's write to a blocked App (app_blocked), or an unavailable connected user (user_forbidden).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              type: permission_error
              code: forbidden
              message: "Insufficient permissions"

    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              type: authentication_error
              code: unauthorized
              message: "Invalid or missing authentication"
