> For the complete documentation index, see [llms.txt](https://docs.photoroom.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.photoroom.com/getting-started/integrating-with-claude-code-or-codex.md).

# Integrating with Claude Code or Codex

AI coding agents such as [Claude Code](https://claude.com/claude-code) or [Codex](https://openai.com/codex/) are a fast way to integrate the Photoroom API: you describe the result you want and the agent writes, runs and debugs the code for you.

To get good results, the agent needs to know how the Photoroom API works.&#x20;

This page gives you a pre-made prompt that contains everything the coding agent needs: endpoints, authentication, the most useful parameters, limits, and where to look for more details.

{% hint style="info" %}
This documentation is built to be read by agents. Every page is available as Markdown by appending `.md` to its URL, the full index is at [llms.txt](https://docs.photoroom.com/llms.txt), and the [OpenAPI specification](https://image-api.photoroom.com/openapi) lists every parameter. The prompt below teaches the agent to use these sources on its own.
{% endhint %}

### Step 1: Get an API key

If you don't have an API key yet, follow the [steps to create yours](/getting-started/introduction.md#how-can-i-get-my-api-key).

While the agent is prototyping, we recommend using Sandbox mode: prepend `sandbox_` to your API key and calls are free (results are watermarked).

Store the key in an environment variable rather than pasting it into the conversation, so that it never ends up in your code or in your Git history:

```bash
export PHOTOROOM_API_KEY="sandbox_xxxxxxxxxxxxxxxx"
```

### Step 2: Copy the prompt

Copy the prompt below and paste it into Claude Code or Codex, followed by a description of what you want to build (see the examples in Step 3).

{% code title="Photoroom API prompt for coding agents" overflow="wrap" %}

```
You are going to integrate the Photoroom API. Everything you need to know is below. Read it fully before writing code.

# 1. Documentation sources (use them when you need details not covered here)

- Full index of the documentation: https://docs.photoroom.com/llms.txt
- Any documentation page is available as Markdown by appending `.md` to its URL, for example https://docs.photoroom.com/image-editing-api-plus-plan/ai-shadows.md
- Ask the documentation a question in natural language: GET https://docs.photoroom.com/getting-started/introduction.md?ask=<your question>
- OpenAPI specification with every endpoint and parameter: https://image-api.photoroom.com/openapi
- Do not guess parameter names or values: if a parameter is not listed in this prompt, fetch the relevant documentation page or the OpenAPI spec first.

# 2. Authentication

- Every request needs the header `x-api-key: <API_KEY>`.
- The API key is in the environment variable PHOTOROOM_API_KEY. Never hardcode it, never print it, never commit it.
- Sandbox mode: an API key prefixed with `sandbox_` makes free calls (1,000 per month, 100 per day) that return a watermarked image. Use it for all tests and development. The production key (without the prefix) consumes credits.
- A missing or invalid key returns HTTP 401; a key that is not allowed (or a credit balance of zero) returns HTTP 403 with body {"error":{"message":"Unauthorized"}}.
- Check the account and remaining credits with GET https://image-api.photoroom.com/v2/account (returns {"images":{"available":N,"subscription":N},"plan":"..."}).

# 3. The two APIs

## Image Editing API (Plus plan) — use this by default
POST https://image-api.photoroom.com/v2/edit   (multipart/form-data, input as a file in `imageFile`)
GET  https://image-api.photoroom.com/v2/edit   (query string, input as a public URL in `imageUrl`)
Both endpoints accept the same parameters. Use POST for local files, GET for images already hosted online.
- Input: PNG, JPEG or WEBP, max 30 MB, max 5,000 px on the widest side (larger images are downscaled).
- Output: the response body is the image bytes (PNG by default). Save the body directly to a file; do not try to parse it as JSON unless the status code is not 200.
- One image per call. Edits can be combined in a single call.
- Response headers worth reading: `x-uncertainty-score` (0 = confident cutout, 1 = unsure, -1 = image contains humans).

## Remove Background API (Basic plan) — only if the user has a Basic plan or only needs background removal
POST https://sdk.photoroom.com/v1/segment   (multipart/form-data, input as a file in `image_file`)
- Parameters: format (png|jpg|webp, default png), channels (rgba|alpha), bg_color (hex like #FFFFFF or color name), size (preview|medium|hd|full), crop (true|false), despill (true|false).
- Input: PNG, JPEG, WEBP or HEIC, max 50 MB, max 6,000 px on the widest side.
- Output: image bytes. EXIF metadata is not preserved, so apply EXIF rotation to the input before sending it.
- Base64 input is also accepted as JSON: {"image_file_b64": "..."} with Content-Type: application/json.

# 4. Image Editing API — parameters you will use most

Parameters are grouped by feature using dot notation. Send them as form fields (POST) or query parameters (GET). Booleans are the strings `true`/`false`.

Input
- imageFile (POST) or imageUrl (GET): the image to edit. Required unless imageFromPrompt.prompt is used.
- removeBackground: true (default) | false. Set to false to keep the original background and only apply other edits.

Feature headers (HTTP headers, NOT form fields — send them next to x-api-key)
Some features select a model or enable a mode through a request header. These are headers on the HTTP request, not parameters in the body or query string.
- pr-ai-background-model-version: selects the AI Backgrounds model used with background.prompt. Values: 3 (current default), background-studio-beta-2025-03-17 (recommended: more photorealistic, better textures and props, a bit slower), 2 (deprecated; the only model that honours background.negativePrompt).
- pr-ai-shadows-model-version: 2026-04-15 selects the new AI Shadows model. Required to use shadow.mode=ai.auto-with-overrides and the shadow.*Override parameters (softnessOverride, intensityOverride, spreadOverride, directionOverride, subjectPoseOverride). Without this header, only the legacy modes ai.soft | ai.hard | ai.floating work; with it, use ai.auto-with-overrides, ai.preset-soft or ai.preset-hard.
- pr-hd-background-removal: auto enables HD Background Removal, recommended for high-resolution inputs (≥ 2K) to get more detailed subject edges.
- pr-ai-upscale-model-version: ai-upscale-2025-07-29 gives early access to the newer model for upscale.mode=ai.fast.
Headers and parameters must match: sending shadow.*Override parameters without the shadows header, or ai.soft with the header, will fail or be ignored. When copying an example from a documentation page, copy its --header lines too.

Background (only when removeBackground=true)
- background.color: hex without `#` (FFFFFF, FF0000EE) or color name (white, red). Omit for a transparent background.
- background.prompt: text prompt to generate an AI background (e.g. "on a marble kitchen counter, soft morning light"). Add background.expandPrompt=ai.auto to let the API enrich short prompts. background.seed for reproducible results. For best results also send the header pr-ai-background-model-version: background-studio-beta-2025-03-17.
- background.imageUrl (GET) / background.imageFile (POST): use a static image as background. background.scaling: fill (default) | fit.
- background.blur.mode: gaussian | bokeh, with background.blur.radius (0 to 0.05).

Shadows and lighting
- shadow.mode: recommended — set header pr-ai-shadows-model-version: 2026-04-15 and shadow.mode=ai.auto-with-overrides (the model picks the best shadow; optionally fine-tune with shadow.softnessOverride 0–1, shadow.intensityOverride 0–1, shadow.spreadOverride short|medium|long or degrees, shadow.directionOverride behind|behindLeft|left|frontLeft|front|frontRight|right|behindRight or degrees, shadow.subjectPoseOverride flatlay|upright or degrees). Legacy modes without the header: ai.soft | ai.hard | ai.floating.
- lighting.mode: ai.auto | ai.preserve-hue-and-saturation | ai.optimize-portrait (AI Relight).

Size and positioning
- outputSize: originalImage (default) | croppedSubject | WIDTHxHEIGHT (e.g. 1000x1000).
- padding: 0 to 0.49, or "15%", or "100px". Space around the subject; per-side variants paddingTop/paddingBottom/paddingLeft/paddingRight.
- margin: same formats as padding, but never ignored on cropped sides; per-side variants marginTop/etc.
- scaling: fit (default) | fill.
- horizontalAlignment: left | center | right. verticalAlignment: top | center | bottom.
- maxWidth / maxHeight: resize while keeping aspect ratio (only with outputSize originalImage or croppedSubject).
- ignorePaddingAndSnapOnCroppedSides: true (default) | false.

Other edits
- textRemoval.mode: ai.artificial (watermarks, prices, logos added in post) | ai.natural (text physically in the scene) | ai.all.
- expand.mode: ai.auto — fills transparent/padding areas by extending the background (use with removeBackground=false or a static background and a larger outputSize).
- uncrop.mode: ai.auto — regenerates the missing parts of a cropped subject.
- upscale.mode: ai.fast | ai.slow (preview feature, up to 4x; input limits apply).
- beautify.mode: ai.auto (packshot) | ai.food | ai.car — improves product/food/car images; not for humans or pets.
- editWithAI.mode=ai.auto with editWithAI.prompt: free-form natural-language edit of the image.
- imageFromPrompt.prompt: generate an image from text instead of editing an input image.
- Other features (flatLay.*, ghostMannequin.*, virtualModel.*, ironing.mode, outline.*, segmentation.*, templateId, layers) are documented at https://docs.photoroom.com/llms.txt — fetch the page before using them.

Export
- export.format: png (default) | jpeg | webp | avif. JPEG does not support transparency: always set background.color when exporting to JPEG.
- export.dpi: 72 to 1200.
- preserveMetadata: never (default) | xmp.

Reference example (product packshot on white with a soft shadow):
    curl --request POST \
      --url https://image-api.photoroom.com/v2/edit \
      --header "x-api-key: $PHOTOROOM_API_KEY" \
      --header "pr-ai-shadows-model-version: 2026-04-15" \
      --form imageFile=@/absolute/path/to/image.jpg \
      --form background.color=FFFFFF \
      --form padding=0.15 \
      --form shadow.mode=ai.auto-with-overrides \
      --form outputSize=1600x1600 \
      --form export.format=jpeg \
      --output result.jpg

# 5. Errors, limits and behaviour to implement

- HTTP 200: body is the image. Any other status: body is a JSON error, usually {"error":{"message":"..."}} (the Remove Background API may return {"detail":"..."} instead). Always check the status code before writing the body to disk, and log the error message.
- 400: invalid parameter or incompatible combination (e.g. JPEG export with transparency, background.imageUrl with removeBackground=false). Fix the request; do not retry as-is.
- 401/403: authentication problem or no credits left. Do not retry.
- 402: payment required (no credits). Do not retry.
- 429: rate limit. Default limit is 60 images per minute. Back off and retry with exponential delay.
- 500 or network timeout: retry up to 3 times with exponential backoff (e.g. 2s, 4s, 8s).
- AI features (backgrounds, relight, shadows, uncrop, expand, upscale) take longer than plain background removal; set the HTTP client timeout to at least 60 seconds. Large images take longer.
- Bulk processing: the API handles one image per call; run calls in parallel but stay under the rate limit (e.g. a worker pool of 5 to 10 with a token bucket).
- Never overwrite the original images; write results to a separate output directory, keeping the original file names.
- Each successful production call consumes credits, so avoid re-processing images that already have a result (check for an existing output file first).

# 6. How to work

1. Confirm the API key is present in PHOTOROOM_API_KEY and check it with GET /v2/account before doing anything else.
2. Use a sandbox_ key for all development and tests. Ask before switching to a production key.
3. Test on a single image first, save the result, and verify it (open it or check that it is a valid image of the expected dimensions) before processing more.
4. Prefer the platform's standard HTTP client (curl, fetch, requests, URLSession…) with multipart/form-data; no SDK is required.
5. When a result does not look right, read the relevant feature page (append .md to its URL) or ask the documentation using the ?ask= query before changing parameters at random.
```

{% endcode %}

### Step 3: Describe what you want to build

Right after the prompt, tell the agent what you need. The more precise you are about the input, the desired output, and the language or framework, the better. For example:

* "Write a Python script that processes every JPEG in `./products`, removes the background, puts the subject on a white background with 15% padding and a soft shadow, and saves the results as 1600x1600 JPEGs in `./output`."
* "Add an API route to this Next.js app that accepts an uploaded image, sends it to the Photoroom API to generate an AI background from a prompt provided by the user, and returns the resulting image."
* "Create a Swift function for my iOS app that calls the Remove Background API and returns a `UIImage` with a transparent background."
* "I need product images that comply with Google Shopping requirements: white background, the product filling 75 to 90% of the frame, no text. Write a script that does this for a CSV of image URLs."

A few features (the newest [AI Shadows](/image-editing-api-plus-plan/ai-shadows.md) and [AI Backgrounds](/image-editing-api-plus-plan/ai-backgrounds.md) models, [HD Background Removal](/image-editing-api-plus-plan/hd-background-removal.md), the early-access [AI Upscale](/image-editing-api-plus-plan/preview-ai-upscale.md) model) are selected with an HTTP header such as `pr-ai-shadows-model-version` rather than a parameter.&#x20;

The prompt above covers them, but if you point the agent at a specific feature page, ask it to reproduce the `--header` lines of the examples, not just the `--form` parameters.

### Step 4 (optional): Make the instructions permanent

If you plan to work on your Photoroom integration over several sessions, save the prompt in your repository so the agent loads it automatically:

{% tabs %}
{% tab title="Claude Code" %}
Save the prompt as a file in your project (for example `docs/photoroom-api.md`) and reference it from your `CLAUDE.md`:

```markdown
# Photoroom API
When working with the Photoroom API, read and follow @docs/photoroom-api.md
```

Alternatively, save it as a skill in `.claude/skills/photoroom-api/SKILL.md` with a short frontmatter, so that Claude Code loads it only when the task involves the Photoroom API:

```markdown
---
name: photoroom-api
description: How to call the Photoroom Image Editing API and Remove Background API. Use whenever the task involves editing images, removing backgrounds, or the Photoroom API.
---

(paste the prompt here)
```

{% endtab %}

{% tab title="Codex" %}
Save the prompt as a file in your project (for example `docs/photoroom-api.md`) and reference it from your `AGENTS.md`:

```markdown
# Photoroom API
When working with the Photoroom API, read and follow the instructions in docs/photoroom-api.md
```

Codex reads `AGENTS.md` at the root of the repository (and in subdirectories) at the start of each session.
{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Never write your API key into `CLAUDE.md`, `AGENTS.md`, or any committed file. Keep it in the `PHOTOROOM_API_KEY` environment variable, or in a `.env` file that is listed in your `.gitignore`.
{% endhint %}

### Prefer a no-code approach?

If you want to edit images from a conversation rather than write code, the Photoroom API is also available as an MCP server that you can add as a custom connector in Claude. See the instructions at [photoroom.com/api/claude](https://www.photoroom.com/api/claude).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.photoroom.com/getting-started/integrating-with-claude-code-or-codex.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
