> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.joytokens.ai/llms.txt.

# Image Generations

POST https://api.joytokens.ai/openai/v1/images/generations
Content-Type: application/json

Generates images from a text prompt using an OpenAI-compatible request. Model and prompt are required. JoyToken forwards supported image options to the selected provider and appends routing and billing details under metadata. This endpoint is non-streaming: do not send stream: true. JoyToken returns one application/json response after generation completes and never emits SSE events or [DONE].


Reference: https://docs.joytokens.ai/open-api/api-reference/compatible-model-ap-is/images/generate-image

## Authentication

- `Authorization` header (bearer token, required) — Use `Authorization: Bearer $JOY_TOKEN_API_KEY`.

## Request

### Headers

- `X-Request-ID` (string, optional) — Optional request identifier for deduplication, billing, logs, and debugging correlation.

### Body (application/json)

This endpoint expects an ImageGenerationRequest.

- `model` (string, required) — Use `auto` to let the gateway pick the image model, or pass a concrete `modelName` from the model catalog to pin that model. Both ways are available to every account.
- `prompt` (string, required) — Text description of the image to generate.
- `n` (integer, optional) — Number of images to generate. Provider limits vary.
- `quality` (string, optional) — Provider-supported image quality, such as standard, hd, medium, or high.
- `response_format` (enum, optional) — Output mode. Defaults to `b64_json` (base64 in `data[].b64_json`). Set `url` to receive a hosted image URL in `data[].url` instead; this only works when every eligible image model supports URL output, otherwise JoyToken falls back to `b64_json`. Omit unless you specifically need URL output.
  - Allowed values: `url`, `b64_json`
- `size` (string, optional) — Provider-supported output dimensions, for example 1024x1024.
- `style` (string, optional) — Provider-supported image style.
- `user` (string, optional) — Optional end-user identifier.
- `background` (string, optional) — Provider-supported background mode.
- `moderation` (string, optional) — Provider-supported moderation setting.
- `output_compression` (integer, optional) — Compression percentage for supported output formats.
- `output_format` (string, optional) — Provider-supported image format, such as png, jpeg, or webp.

## Response

### 200

Successful non-streaming image generation result returned as one application/json document.

- `data` (list of GeneratedImage, required)
- `created` (long, optional) — Unix timestamp for the generation result.
- `metadata` (JoyTokenMetadata, optional) — JoyToken routing and billing metadata appended by the gateway when available. In orchestration (multi-task planning) mode this object also carries per-task identifiers, and the response returns one metadata object per task.

## Errors

### 400 Bad Request Error

Invalid JSON, missing model or prompt, or unsupported request parameters.

- `error` (ErrorResponseError, required)

### 401 Unauthorized Error

Missing, invalid, revoked, or expired API key.

- `error` (ErrorResponseError, required)

### 402 Payment Required Error

Insufficient wallet balance or billing freeze failure.

- `error` (ErrorResponseError, required)

### 403 Forbidden Error

Request blocked by API key policy, IP policy, model blacklist, or route strategy.

- `error` (ErrorResponseError, required)

### 409 Conflict Error

Duplicate X-Request-ID within the deduplication window.

- `error` (ErrorResponseError, required)

### 429 Too Many Requests Error

Rate limit exceeded.

- `error` (ErrorResponseError, required)

### 500 Internal Server Error

Internal gateway or provider error.

- `error` (ErrorResponseError, required)

## Types

### GeneratedImage

- `url` (string, optional) — URL for the generated image when response_format is url.
- `b64_json` (string, optional) — Base64-encoded image data when response_format is b64_json.
- `revised_prompt` (string, optional) — Provider-revised prompt, when returned.

### JoyTokenMetadata

JoyToken routing and billing metadata appended by the gateway when available. In orchestration (multi-task planning) mode this object also carries per-task identifiers, and the response returns one metadata object per task.

- `model` (string, optional) — Final model used. May be `auto` for aggregation tasks, or a concrete sub-model (for example `Gemini-3-Flash-Preview`, `gpt-5.6-luna`) that executed a specific task.
- `tier` (enum, optional) — JoyToken model tier.
  - Allowed values: `economy`, `standard`, `premium`
- `score` (double, optional)
- `billing_id` (string, optional) — Billing account identifier. Present in orchestration metadata events.
- `tag` (list of string, optional) — Role tags describing what a task did. Present in orchestration mode. Common values include orchestration, search, reasoning, writing, and aggregation.
- `task_id` (string, optional) — Task identifier. Reserved values are `__planner__` and `__final__`.
- `task_seq` (integer, optional) — Execution sequence of the task. `0` is the planner.
- `task_status` (enum, optional) — Task lifecycle status.
  - Allowed values: `DONE`
- `title` (string, optional) — Human-readable task title from the plan.
- `billing` (JoyTokenMetadataBilling, optional)
- `usage` (map from string to any, optional) — Provider usage plus JoyToken credits_used when available.
- `latency` (JoyTokenMetadataLatency, optional) — Latency breakdown. Orchestration tasks report first_token_ms and stream_ms.
- `request_id` (string, optional) — Gateway request identifier for log, billing, and debugging correlation. Present on non-streaming top-level metadata.
- `model_recommendation` (JoyTokenMetadataModelRecommendation, optional) — Router's model recommendation for this request, including candidate models and their scores.
- `task_score` (JoyTokenMetadataTaskScore, optional) — Router scoring breakdown used to select the model.

### ErrorResponseError

- `message` (string, required)
- `type` (string, optional)
- `code` (ErrorResponseErrorCode, optional, nullable)

### JoyTokenMetadataBilling

- `credits_used` (string, optional)
- `input_tokens` (integer, optional)
- `output_tokens` (integer, optional)
- `cached_input_tokens` (integer, optional)
- `cached_output_tokens` (integer, optional)

### JoyTokenMetadataLatency

Latency breakdown. Orchestration tasks report first_token_ms and stream_ms.

- `routing_ms` (integer, optional)
- `first_token_ms` (integer, optional)
- `stream_ms` (integer, optional)

### JoyTokenMetadataModelRecommendation

Router's model recommendation for this request, including candidate models and their scores.

- `models` (list of JoyTokenMetadataModelRecommendationModelsItems, optional)

### JoyTokenMetadataTaskScore

Router scoring breakdown used to select the model.

- `history_score` (double, optional)
- `latest_conversation_score` (double, optional)
- `multimodal_score` (double, optional)
- `system_score` (double, optional)
- `tool_score` (double, optional)
- `total_score` (double, optional)

### ErrorResponseErrorCode

- string
- integer

### JoyTokenMetadataModelRecommendationModelsItems

- `model_id` (string, optional)
- `probability` (double, optional)
- `selected` (boolean, optional)
- `feature_tags` (list of string, optional)

## Examples

**Request**

```json
{
  "model": "auto",
  "prompt": "A neon JoyToken logo on a black background",
  "n": 1,
  "size": "1024x1024"
}
```

**Response**

```json
{
  "data": [
    {
      "url": "https://example.com/generated.png",
      "revised_prompt": "A neon JoyToken logo on a black background"
    }
  ],
  "created": 1793395200,
  "metadata": {
    "model": "auto",
    "tier": "standard",
    "billing": {
      "credits_used": "1.25"
    },
    "usage": {
      "credits_used": "1.25"
    }
  }
}
```

**SDK Code**

```python Images_generateImage_example
import requests

url = "https://api.joytokens.ai/openai/v1/images/generations"

payload = {
    "model": "auto",
    "prompt": "A neon JoyToken logo on a black background",
    "n": 1,
    "size": "1024x1024"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Images_generateImage_example
const url = 'https://api.joytokens.ai/openai/v1/images/generations';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"auto","prompt":"A neon JoyToken logo on a black background","n":1,"size":"1024x1024"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Images_generateImage_example
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.joytokens.ai/openai/v1/images/generations"

	payload := strings.NewReader("{\n  \"model\": \"auto\",\n  \"prompt\": \"A neon JoyToken logo on a black background\",\n  \"n\": 1,\n  \"size\": \"1024x1024\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Images_generateImage_example
require 'uri'
require 'net/http'

url = URI("https://api.joytokens.ai/openai/v1/images/generations")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"auto\",\n  \"prompt\": \"A neon JoyToken logo on a black background\",\n  \"n\": 1,\n  \"size\": \"1024x1024\"\n}"

response = http.request(request)
puts response.read_body
```

```java Images_generateImage_example
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.joytokens.ai/openai/v1/images/generations")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"auto\",\n  \"prompt\": \"A neon JoyToken logo on a black background\",\n  \"n\": 1,\n  \"size\": \"1024x1024\"\n}")
  .asString();
```

```php Images_generateImage_example
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.joytokens.ai/openai/v1/images/generations', [
  'body' => '{
  "model": "auto",
  "prompt": "A neon JoyToken logo on a black background",
  "n": 1,
  "size": "1024x1024"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Images_generateImage_example
using RestSharp;

var client = new RestClient("https://api.joytokens.ai/openai/v1/images/generations");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"auto\",\n  \"prompt\": \"A neon JoyToken logo on a black background\",\n  \"n\": 1,\n  \"size\": \"1024x1024\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Images_generateImage_example
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "auto",
  "prompt": "A neon JoyToken logo on a black background",
  "n": 1,
  "size": "1024x1024"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.joytokens.ai/openai/v1/images/generations")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```