Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Create an image-generation API key in your provider’s developer dashboard—not in an image prompt or inside a model request. For OpenAI, create a project key in the API Keys area, copy it once into a secure secret store, expose it to your backend as OPENAI_API_KEY, and keep every request that uses the secret off the client. Then choose the Image API for one-shot generation or editing, or the Responses API image-generation tool for conversational, multi-step work.

What an image-generation API key is

An API key is a credential that authorizes software to call an image service on your account. The key is created and managed in the provider dashboard; it is not generated by the prompt, model name, or image request. Whoever obtains an unrestricted key may be able to consume your quota, create charges, or access data permitted by that key.

The safe architecture is therefore:

  1. Your browser or mobile app sends a request to your server.
  2. Your server reads the key from its environment or a secret manager.
  3. Your server adds the provider’s authorization header and calls the image API.
  4. Your server returns only the result needed by the client.

Never put a secret key in JavaScript shipped to users, a mobile-app bundle, a public repository, a support ticket, or chat.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create an OpenAI project API key

1. Open the developer dashboard

Sign in to the OpenAI developer platform and open the API Keys or project dashboard area. If you work with more than one organization or project, select the one that should own the image requests before creating the key.

2. Create a narrowly scoped key

Choose the control to create a project API key. Give it a recognizable name such as image-staging-backend. Select the narrowest permissions the dashboard makes available for the job, and set an expiration date when that option is offered. A separate key for development, staging, and production makes ownership and incident response much clearer than one shared credential.

3. Copy the secret once

Copy the secret immediately and place it in a password-protected local secret store or your deployment platform’s secret manager. Treat the value as unrecoverable after the creation screen: if you lose it, create a replacement rather than searching source files or logs for it.

Set OPENAI_API_KEY on the backend

macOS and Linux

export OPENAI_API_KEY="your_api_key_here"

This sets the variable for processes launched from that shell. For a persistent development setup, use your operating system’s protected keychain or a local environment file that is excluded from version control; do not commit that file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Windows PowerShell

setx OPENAI_API_KEY "your_api_key_here"

setx affects newly started processes. Open a new PowerShell window before testing. If your program still reports a missing key, check the variable in the same shell or service process that launches the application.

Check presence without revealing the secret

Test only whether a value exists. Do not print the key itself.

python -c "import os; print('set' if os.getenv('OPENAI_API_KEY') else 'missing')"

In production, configure the variable through your hosting provider’s secret settings, container secret mechanism, or a dedicated secrets manager. Keep it out of build-time frontend variables, browser storage, analytics events, exception reports, and request URLs.

Use the key from an official SDK

The official clients read OPENAI_API_KEY from the environment in the standard setup. The following examples show the initialization pattern; install the current official SDK for your language and follow its current image-model documentation for model availability and parameters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python

import os
from openai import OpenAI

if not os.getenv("OPENAI_API_KEY"):
    raise RuntimeError("OPENAI_API_KEY is not set")

client = OpenAI()

# Use the Image API for a single generation or edit.
result = client.images.generate(
    model="your-approved-image-model",
    prompt="A clean editorial illustration of a mountain observatory at dawn"
)
print(result)

Replace the model placeholder with an image model enabled for your project. Keep the call on a server process. Save binary image data according to the response format documented for that model rather than logging the complete response when it may contain sensitive inputs or output metadata.

Node.js

import OpenAI from "openai";

if (!process.env.OPENAI_API_KEY) {
  throw new Error("OPENAI_API_KEY is not set");
}

const client = new OpenAI();
const result = await client.images.generate({
  model: "your-approved-image-model",
  prompt: "A clean editorial illustration of a mountain observatory at dawn"
});
console.log(result);

Use the package’s current documented response handling to download or persist the returned image. Do not send the key to a browser route or include it in a client-side bundle.

Command-line workflows

For a command-line test, prefer the provider’s current CLI or SDK examples so the endpoint, authentication header, and response encoding match the selected image model. Keep the key in OPENAI_API_KEY and avoid putting it directly in shell history. If you must use an HTTP client, pass the authorization value through an environment variable and write the binary response to a file rather than a terminal.

Choose the right image surface

Requirement Recommended surface Why
One image generation Image API Direct request for a single generated image.
One image edit Image API Designed for generation or editing workflows.
Conversational or multi-turn creation Responses API image-generation tool Maintains a broader response workflow for iterative, multi-step tasks.

Organization verification may be required for GPT Image models. If a key is valid but a model call is rejected, check project access and verification status before changing code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Design the backend boundary

Keep authorization server-side

Your public endpoint should accept only the inputs your application needs, validate prompt length and file types, and add the provider authorization header internally. Return a job identifier or image result to the caller without exposing environment variables or upstream headers.

Separate environments and permissions

  • Use distinct projects or keys for development, staging, and production.
  • Give each key a descriptive owner and purpose.
  • Choose the smallest permission set available.
  • Set expiration dates where supported and rotate before expiry.
  • Configure spend limits and monitor usage.
  • Use IP allowlisting when the deployment and provider support it.

Plan revocation

If a key appears in a commit, browser bundle, log, screenshot, or ticket, revoke it immediately and create a replacement. Removing the text from the latest commit is not enough: cached builds, forks, logs, and history may still contain it. After rotation, redeploy every service that used the old value and confirm the old key can no longer authenticate.

Why a request fails after key creation

“API key not found” or missing-credential errors

  • Confirm OPENAI_API_KEY exists in the same process that starts the application.
  • After using PowerShell setx, open a new shell.
  • Check that your process manager, container, CI job, or serverless platform received the secret.
  • Do not fix the problem by hard-coding the value in source code.

Unauthorized or forbidden responses

  • Verify that the key belongs to the intended organization and project.
  • Check whether it expired or was revoked.
  • Confirm its permissions include the operation your code requests.
  • Check organization verification requirements for the selected GPT Image model.

Model or capability errors

A working key does not grant every model or feature. Confirm the exact model identifier, image-generation surface, input type, and project access in the provider’s current documentation. Use the Image API for a single generation or edit; use the Responses API tool when your application needs conversational or multi-step image work.

Timeouts, rate limits, and intermittent failures

Inspect the HTTP status, SDK exception, and provider request ID. Retry only failures that are safe to retry, with bounded exponential backoff and an idempotency strategy appropriate to the operation; otherwise a retry may create duplicate images or charges. Set a client timeout long enough for image generation, but cap it so stalled requests do not exhaust your workers. Record timing, status, and request ID—not the prompt if it contains personal data, and never the secret.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Unexpected spend or quota use

Check usage by project and key, review spend limits, and look for a leaked browser bundle, public repository, CI log, or proxy endpoint. Revoke exposed credentials first, then investigate. Network restrictions and separate production keys reduce the blast radius but do not replace monitoring.

Operational checklist before production

  • The key was created in the intended project and has a descriptive name.
  • Permissions are minimal and an expiration date is configured when available.
  • The secret is stored in a password manager or deployment secret manager.
  • Only backend code can read OPENAI_API_KEY.
  • Development, staging, and production use separate credentials.
  • Usage monitoring, spend limits, and suitable IP restrictions are enabled.
  • Logs contain status and request IDs, never authorization headers or full secrets.
  • There is a documented revoke-and-redeploy procedure.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If what you actually need is a clean screenshot of a web page rather than a generated illustration, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF, and the service accepts cookie or consent banners before removing more than 60 known consent platforms, newsletter popups, and chat widgets. You can disable each cleanup step when necessary.

Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response reports the result in X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

See the ScreenshotNeo documentation for all options. This call captures a page as a WebP file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo includes full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets and arbitrary viewports, retina scale, PDF paper size/margins/orientation/page ranges, HTML/CSS-to-image, custom CSS and JavaScript, pre-capture clicks, hidden selectors, selector/delay/network-idle waits, ad/tracker/request/resource blocking, custom headers/cookies/user agent/Authorization, timezone and geolocation, transparent backgrounds, resizing, chosen-TTL caching, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, an OpenAPI specification, and compatibility with parameter names used by other screenshot APIs.

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create your free ScreenshotNeo account.

FAQ

Can I use one API key in both my frontend and backend?

No. A browser-delivered key can be copied and abused. Keep the provider key on your server and expose only your own authenticated endpoint to the frontend.

Should I create a new key for every request?

No. Create managed keys per environment or service, set appropriate expiration and permissions, and rotate them on a schedule or after exposure.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What should I record when support asks about a failed request?

Provide the timestamp, HTTP status, SDK exception, project context, and provider request ID. Redact authorization headers, key values, personal data, and sensitive prompts.

Frequently Asked Questions

Can I use one API key in both my frontend and backend?

No. A browser-delivered key can be copied and abused. Keep the provider key on your server and expose only your own authenticated endpoint to the frontend.

Should I create a new key for every request?

No. Create managed keys per environment or service, set appropriate expiration and permissions, and rotate them on a schedule or after exposure.

What should I record when support asks about a failed request?

Provide the timestamp, HTTP status, SDK exception, project context, and provider request ID. Redact authorization headers, key values, personal data, and sensitive prompts.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.