How to Submit Generation Tasks to APIMart Using GPT-Image2: A Complete Technical Guide
Submit generation tasks to APIMart using GPT-Image2 by sending a POST request to /api/generate-image with your prompt and case ID, which triggers an async pipeline that validates input, reserves credits, and forwards the request to APIMart's /v1/images/generations endpoint, returning a taskId for polling.
GPT-Image2 provides a streamlined interface for async image generation through APIMart's distributed infrastructure. The integration handles credit reservation, payload transformation, and webhook management automatically. This guide explains the exact mechanism for submitting generation tasks to APIMart using GPT-Image2's serverless API layer, referencing the actual implementation in the freestylefly/awesome-gpt-image-2 repository.
Prerequisites and Configuration
Before submitting tasks, you must configure the APIMart API key. In api/_lib/apimart.js, the server checks process.env.APIMART_API_KEY during initialization. If this variable is missing, the generation endpoint disables itself via the isServerConfigured guard.
Set your environment variable:
export APIMART_API_KEY="your_apimart_api_key_here"
The system also enforces a maximum prompt length of 10,000 characters, defined as APIMART_MAX_PROMPT_LENGTH in shared/apimart.js.
The Submission Pipeline
When you POST to /api/generate-image, the handler in api/generate-image.js executes a six-stage pipeline:
Input Validation and Credit Reservation
First, the endpoint validates the prompt length against APIMART_MAX_PROMPT_LENGTH (10,000 characters). Then it calls reserveGeneration to lock your credit quota. This prevents race conditions and ensures you have sufficient balance before invoking the paid APIMart service.
Payload Construction
The buildApimartGenerationPayload function in shared/apimart.js constructs the JSON body required by APIMart. It includes the target model, sanitized prompt text, output resolution, and optional webhook URL and language parameters.
API Submission to APIMart
The submitApimartGeneration function in api/_lib/apimart.js handles the actual HTTP POST to https://api.apimart.ai/v1/images/generations. It injects the API key into the Authorization header, parses the JSON response, and extracts the task_id. The function returns a normalized object: { taskId, status: 'submitted' }.
Task Storage and Client Response
After successful submission, the handler updates the generation_reservations table row with provider: 'apimart' and the returned taskId. The endpoint responds with HTTP 202 and a JSON payload containing ok: true, the taskId, current status, and user context.
Implementation Examples
Client-Side Task Submission
Submit a generation task from any JavaScript environment:
fetch('https://gpt-image2.canghe.ai/api/generate-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompt: 'A futuristic city skyline at sunset, ultra-realistic, 4k',
caseId: 310,
language: 'en'
})
})
.then(r => r.json())
.then(data => {
if (data.ok) {
console.log('Task submitted:', data.taskId);
} else {
console.error('Generation error:', data.error);
}
});
Polling for Completion
Use the returned taskId to poll for results:
async function pollTask(taskId) {
while (true) {
const res = await fetch(`https://gpt-image2.canghe.ai/api/generation?taskId=${taskId}`);
const { status, image } = await res.json();
if (status === 'completed') return image;
if (status === 'failed') throw new Error('Generation failed');
await new Promise(r => setTimeout(r, 2000));
}
}
Server-Side Direct Integration
For custom server implementations, bypass the HTTP layer and use the internal libraries directly:
import { submitApimartGeneration } from './api/_lib/apimart.js';
import { buildApimartGenerationPayload } from './shared/apimart.js';
const payload = buildApimartGenerationPayload('A dreamy night forest', {
language: 'en',
webhook: 'https://myapp.example.com/webhook'
});
const result = await submitApimartGeneration({
apiKey: process.env.APIMART_API_KEY,
prompt: payload.prompt,
language: payload.language,
webhook: payload.webhook
});
console.log('APIMart task ID:', result.taskId);
Error Handling and Debugging
Errors from APIMart are normalized in api/generate-image.js using apimartErrorCode mapping to publicErrorCode. This translation layer ensures that internal APIMart error codes convert to user-friendly messages without exposing sensitive implementation details.
Common error scenarios include:
- Configuration errors: Missing
APIMART_API_KEYdisables the endpoint entirely - Validation errors: Prompts exceeding 10,000 characters return 400 Bad Request
- Credit errors: Insufficient balance triggers a reservation failure before APIMart is contacted
Summary
- Configure the
APIMART_API_KEYenvironment variable to enable the generation endpoint inapi/_lib/apimart.js - Submit tasks via POST to
/api/generate-imagewithprompt,caseId, and optionallanguageparameters - The system automatically validates input length against
APIMART_MAX_PROMPT_LENGTH(10,000 characters) defined inshared/apimart.js - Internal functions
buildApimartGenerationPayloadandsubmitApimartGenerationhandle APIMart API communication - Successful submissions return HTTP 202 with a
taskIdfor async polling via/api/generation - Error codes are normalized to protect internal APIMart details while providing actionable client feedback
Frequently Asked Questions
What is the maximum prompt length when submitting to APIMart through GPT-Image2?
The system enforces a hard limit of 10,000 characters defined as APIMART_MAX_PROMPT_LENGTH in shared/apimart.js. Exceeding this limit in your POST request to /api/generate-image results in immediate validation failure before any credits are reserved or APIMart is contacted.
How does GPT-Image2 handle authentication with APIMart?
GPT-Image2 uses the APIMART_API_KEY environment variable, which the submitApimartGeneration function in api/_lib/apimart.js injects into the Authorization header when posting to https://api.apimart.ai/v1/images/generations. If this variable is unset, the isServerConfigured check disables the generation endpoint entirely.
Can I receive webhooks when my image generation completes?
Yes. Pass a webhook URL in your request payload, and buildApimartGenerationPayload includes it in the APIMart request body. Alternatively, poll the /api/generation endpoint using the taskId returned from your initial submission to check status and retrieve the final image URL.
What happens if APIMart returns an error during generation?
Errors are caught in api/generate-image.js and mapped through apimartErrorCode to publicErrorCode, stripping sensitive internal details while preserving actionable information for the client. The endpoint returns a structured error response that the front-end can display without exposing APIMart's internal error signatures.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →