Nostraddeveloper documentationDeveloper consoleYour account

Connect an app to Nostrad

Nostrad gives your app AI models (images, video, speech, music, chat) and a Drive for files through the Nostrad gateway at https://gateway.nostrad.ai, an HTTP API. Your app never holds a supplier key.

Two ways in

Choose per app; an app can use both. Both reach the same models with the same commands; only who pays, and how your app proves who it is, differ.

An API keySign in with Nostrad
Who pays NostradYou, from your own Nostrad balance, for every callEach person using your app, from their own Nostrad balance, within the monthly limit they choose for it
Your app's usersNeed no Nostrad account; you charge them however you likeSign in with their Nostrad account, the way they would sign in with Google
What your app holdsOne key, on your server only (NOSTRAD_API_KEY)A client ID (public), and a client secret for a web server; an access token per person
Pick it forYour own server, scripts, background work, an app with its own accounts and billingAn app whose users already have, or are happy to make, a Nostrad account: Nostrad handles accounts, payment and their Drive
Start hereQuickstart: an API keyQuickstart: Sign in with Nostrad

Sign in with Nostrad is standard OAuth 2.1 (authorization code with PKCE) at https://accounts.nostrad.ai; it gives your app an access token for one person. Either way, every gateway call carries Authorization: Bearer <API key or access token>.

1. Checklist: from nothing to a working app

  1. Have a Nostrad account, and open the developer console. Sign-up isn't open yet: accounts are made by invitation from Nostrad. To ask for one, email support@nostrad.ai and say what you'd like to build.
  2. Create app: give it a name. This is your app on Nostrad; its App ID never changes.
  3. Services: tick the services your app uses.
  4. Make what the way in you chose needs (Two ways in; an app can have both):
    • An API key: API keys, then Create API key. It is shown once; put it in your server's secret store as NOSTRAD_API_KEY, never in code or a file.
    • Sign in with Nostrad: the Sign in with Nostrad page, then Create client, one per program that signs people in. Web server if your app has its own server: you get a client secret, shown once, for the server's secret store. Phone, desktop or browser-only if it has no server: no secret, PKCE alone. Enter the exact return address (redirect URI) your program uses, for example https://your-app.example/oauth/nostrad/callback.
  5. Integration: copy the values into your program. The For your coding agent box there holds everything below for your app, both ways, without any secret.
  6. Run the quickstart for your way by hand: an API key or Sign in with Nostrad. Each goes from nothing to a downloaded image.
  7. Build it: the gateway calls (section 4), and for sign-in the sign-in itself (section 3). A complete sign-in server, ready to deploy, is in section 9. Your app is personal until it goes public: only you can sign in to it.

Once you have an account, nothing else is needed: no request to Nostrad, no key to ask for, no setting outside the console. Stuck? See Getting help.

2. The developer console

The console is at accounts.nostrad.ai/developer/, with the same login as your Nostrad account. Each app has these pages:

PageWhat it holds
OverviewThe App ID, whether the app is personal or public, and how many sign-in clients and API keys it has.
ModelsEvery model your app can use, what it costs, and whether it's running now.
DriveHow your app's files work, the commands for them, and the picker to try.
API keysYour app's API keys: create, limit, rotate and delete them.
IntegrationEvery value your program needs, with worked examples.
PlaygroundRun a model in the browser before you write any code.
LogsEvery call, with its job ID.
UsageWhat your app has used.
Sign in with NostradSign-in clients and their secrets.
ServicesThe services the app may ask for.
MonetizeSelling inside your app: products, subscribers, orders, earnings, notifications and testers.
App settingsThe app's name, links (website, developer, source code, privacy policy, terms) and support email. The name is at most 30 characters, with no emojis and no symbol three times in a row, and is your app's own: another app's name with other capitals, spaces or punctuation is refused (Apple 2.3.7: "Choose a unique app name"). People see them on the consent page, where they connect their Nostrad account to your app; leave Support email empty and your app's support mail goes to your account email, which is never shown to people. A business address you type shows there and on people's purchases only once it's verified. Verify email address sends a 6-digit code to the support email; enter it within 15 minutes (5 tries; a new code at most once a minute). The email your Nostrad account signs in with is verified at once. Changing the support email needs it verified again. The rest of this page is below.
App settings: PriceWhat people who sign in to your app pay, as a percentage over Nostrad's prices, from 0 to 500 (0 to start). You get the difference. The page shows what three of your models then cost a customer; jobs started after you save use it. The consent page says it: "your app charges 30% over Nostrad's prices".
App settings: Adult modelsAllow adult models, off to start. While it's off, models Nostrad marks as adult aren't listed for your app and their jobs answer 403. When it's on, the app is rated 18+ and the consent page says your app may make adult content.
App settings: Age ratingThe App Store's age rating questionnaire: for each kind of content, how often it appears in your app (None, Infrequent or Frequent), and whether it has each feature (such as unrestricted web access or gambling). The answers give the rating, 4+, 9+, 13+, 16+ or 18+, the highest any answer gives, as Apple's do. You can choose a higher rating, never a lower one. The consent page shows the rating and what gave it. An app rated 18+ reaches only people whose Nostrad account says they're 18 or over: anyone else is refused on the consent page, and their jobs answer 403 age_restricted. Adult models are only for people 18 or over too. Answer it before you submit the app.
App settings: App review informationWhat Nostrad's reviewer needs to try your app, as the App Store's App Review information and Google Play's sign-in details ask. A contact (name, email and a phone number in international format, starting with + and the country code). Sign-in required: tick it if people sign in to your app's own account, and give up to 5 sets of sign-in details, each a user name and password for a demo account, or other instructions (a one-time code, a QR code's web address, another service's account). The demo account must not expire, must work from any country and must need no one-time code or two-step login. Notes: anything else that helps, up to 4,000 bytes. Only Nostrad sees it, it's kept encrypted, and you can change it at any time.
App settings: Who can sign inPersonal (only you can sign in), waiting for Nostrad's check, verified (public: anyone with a Nostrad account can sign in), or not verified with Nostrad's reason. Submit for verification needs the website, privacy policy and terms on this page, a typed support email verified (an empty one needs nothing), the age rating answered and the App review information filled in. It opens each of the app's links, and is refused if one doesn't open for anyone: a missing page, an error, a login, a page that doesn't answer within 10 seconds, an address without https, or a PDF or download instead of a web page. Send for review on a verified app's changes needs the App review information too. While it waits, Remove from review takes it back to personal; submitting it again starts the check over. Once it's verified, Unpublish lets nobody new connect to it, while people already connected keep using it; Publish again lets new people in again, with no new check.
App settings: Delete appType the app's name, then Delete app. If nobody else uses it, it's deleted at once. If people use it, nobody new can connect, its subscriptions stop renewing, and it keeps working for them for 90 days, or until the last paid period ends if that's later; their Apps page says when it stops. Until then, Keep the app stops the deletion. Deleting stops the app's sign-ins and API keys, takes its products off sale and frees its name for anyone; its sales and earnings records stay. It can't be undone.
App settings: Messages with NostradShown when Nostrad didn't verify the app, rejected an update or switched the app off, with Nostrad's reason. Reply (up to 4,000 characters) until you send the app again; Nostrad answers here. After a reply, Appeal the decision once if you believe the app follows the App review rules.
Inbox (from your account menu)Messages from people using your apps, in your Inbox. Anyone using your app, or anyone at all once it's public, can write to you from the app's page on their account; you see them by the same ID your app gets for them (usr_...), never their email address, and answer in the conversation, up to 4,000 characters. You can't write to someone first: Announce to the people using your app sends one message to everyone using it, and their answers come back to you as messages. A person can stop your app's messages; then you can't write to them. If they choose Ask Nostrad to help, Nostrad reads the conversation and answers in it, seen by you both. You get an email for a new message, once until you read the conversation (switch it off under Account details, Emails). Never ask anyone for a password, a code or card details in a message.

Client secrets

API keys

An API key calls the Nostrad gateway without anyone signing in, and you pay for every call made with it, from your own Nostrad balance, like a Google Maps key. Use it from a server only: a key in a web page, a phone or desktop program, or shared code can be copied and spent.

3. Sign in with Nostrad

Standard OAuth 2.1 authorization code flow. Any OAuth client library works. The discovery document lists everything below:

https://accounts.nostrad.ai/.well-known/oauth-authorization-server
Value
Issuerhttps://accounts.nostrad.ai
Authorization addresshttps://accounts.nostrad.ai/authorize
Token addresshttps://accounts.nostrad.ai/oauth/token (also revokes: POST token=<token>, see below)
Resourcehttps://gateway.nostrad.ai (RFC 8707: the token is for the Nostrad gateway)
PKCERequired for every client, method S256
Access tokenLasts 1 hour
Refresh tokenLasts until it goes six months without being used

Scopes: the services

Each service is an OAuth scope. Ask for the ones your app uses, separated by spaces. Asking for none means every service the app ticked under Services. Every connected app also has its own folder in the person's Drive, whatever it asks for, so an app that only keeps files (settings, notes, saved work) ticks nothing under Services and asks for nothing: the person then sees only its folder on the consent page, with no spending limit (step by step).

ScopeWhat the person sees
imageMake images
videoMake videos
speechMake speech and use voices
musicMake music
chatChat and write text

On the consent page (Connect your Nostrad account to your app's name) the person sees what your app will be able to see and that it saves files in its own folder in their Drive, can untick services (unticking all of them connects your app with its folder only), and sets a monthly spending limit for your app (100 US dollars unless they change it), then chooses Continue or Cancel. The token response's scope says which services they allowed. Later, on their account page under Apps, they can switch any of those services off (your app's next job for it is refused with 403), change the limit, or take access away. Nostrad emails them when your app has used 80% of their limit and when it reaches it, so they can raise it before your app's jobs are refused. To use a service they didn't allow, send them through sign-in again with it in scope: the new token also covers what they allowed before, and the consent page starts from the limit they already set.

Step 1: send the person to sign in

Make a random code_verifier (43 to 128 characters) and a random state, keep both on your side, then send the browser to:

https://accounts.nostrad.ai/authorize
  ?response_type=code
  &client_id=<your client ID>
  &redirect_uri=<a return address registered on the client, exactly>
  &scope=image%20video
  &state=<state>
  &code_challenge=<BASE64URL(SHA-256(code_verifier))>
  &code_challenge_method=S256
  &resource=https%3A%2F%2Fgateway.nostrad.ai

Step 2: the person comes back

Nostrad sends the browser to your return address with code, state and iss. Check that state is the one you made and that iss is https://accounts.nostrad.ai (RFC 9207). If they chose Cancel, you get error=access_denied instead.

Step 3: swap the code for tokens

Web server client, with its secret as HTTP Basic credentials (client ID and secret each form-encoded first, RFC 6749 §2.3.1). Sending client_id and client_secret in the form body also works.

curl https://accounts.nostrad.ai/oauth/token \
  -u "<client ID>:$NOSTRAD_CLIENT_SECRET" \
  -d grant_type=authorization_code \
  -d code=<code> \
  -d redirect_uri=<the same return address> \
  -d code_verifier=<code_verifier>

Phone, desktop or browser-only client: no secret, send client_id in the form instead of -u.

The answer:

{ "access_token": "...", "token_type": "bearer", "expires_in": 3600,
  "refresh_token": "...", "scope": "image video", "user_id": "usr_4f1c9a..." }

Keep both tokens on your server, tied to that person's session in your app. Never send them to the browser.

Knowing who signed in. user_id is how your app recognises this person: save your data under it. It stays the same each time they sign in, on any device, even if they disconnect your app and come back. Another app gets a different ID for the same person, and it can't be used to find their email or name, which Nostrad doesn't give apps. Don't use the access token for this, since it changes. If the answer has no user_id, get it from GET /v1/key.

Step 4: refresh

curl https://accounts.nostrad.ai/oauth/token \
  -u "<client ID>:$NOSTRAD_CLIENT_SECRET" \
  -d grant_type=refresh_token \
  -d refresh_token=<refresh token>

Use the new refresh token from each answer. Each refresh moves the end of the sign-in to six months on.

When a sign-in stops working

Write your app expecting that a refresh token can stop working. It stops when:

If Nostrad switches the person's account off, the Nostrad gateway answers 401 to their tokens until it's switched back on. If Nostrad switches your app off, its sign-ins stay, but every job is refused until it's switched back on.

A refresh that fails answers invalid_grant: send the person through sign-in again. Signing in again doesn't reset what they allowed.

Disconnecting someone. Call the token address with the refresh token when the person disconnects Nostrad in your app. That ends the whole sign-in, including its access tokens, and your app leaves their Apps list. Sending an access token ends only that access token; the refresh token keeps working and your app stays listed.

curl https://accounts.nostrad.ai/oauth/token \
  -u "<client ID>:$NOSTRAD_CLIENT_SECRET" \
  -d token=<refresh token>

The answer is 200 even when the token is unknown or already revoked.

Errors. The authorization and token addresses answer with standard OAuth errors as JSON: {"error": "...", "error_description": "..."}. On the return address they come as error and error_description in the query.

ErrorWhereMeaningWhat to do
invalid_requestauthorize, tokenA required part is missing or wrong, for example no code_challenge, a method other than S256, or a return address the client doesn't listFix the request
invalid_clienttokenThe client ID or secret is wrong, or the client is deletedCheck the client on the console's Sign in with Nostrad page
invalid_scopeauthorizeA service isn't registered for your appAsk only for services ticked under Services
access_deniedreturn addressThe person chose CancelLet them try again
invalid_granttokenThe code or refresh token is wrong, expired, already used or revoked, or the code_verifier, client or return address doesn't matchSend the person through sign-in again
unsupported_grant_typetokengrant_type isn't authorization_code or refresh_tokenFix the request
server_erroranyA failure on Nostrad's sideTry again later

On the Nostrad gateway, an access token that is expired, revoked or unknown gets 401. Refresh once, and if that answers invalid_grant, ask the person to sign in again.

4. The Nostrad gateway

Address https://gateway.nostrad.ai. Every command needs the person's access token, or one of your API keys:

Authorization: Bearer <access token or API key>

Your app sees only its own jobs and files for the signed-in person (with an API key: its own jobs and files for you). The gateway is for servers: it sends no CORS headers, so a browser page calls your own server, which calls the gateway.

CommandWhat it does
GET /v1/modelsThe models this token may use, with each model's inputs, settings and price
POST /v1/quoteThe most a job would cost: { model, inputs, params }, as for a job. Nothing runs and nothing is charged
GET /v1/voices?model=<id>The voices a speech model takes as voice_id
GET /v1/keyWhat this key (or this sign-in) has used, and each limit that applies, the same fields as OpenRouter's key check
POST /v1/jobsRun a model: { model, inputs, params, webhook?, keep? }. 200 when done at once, 202 while it runs
POST /v1/chat/completionsOpenAI's Chat Completions for chat models, streamed or not, with tools: a chat job underneath, charged and listed like one
GET /v1/jobs/<id>One job, as it is now: a running job is checked with the model when you read it
POST /v1/jobs/<id>/cancelCancel a job that hasn't ended
GET /v1/jobsThis app's jobs for this person, newest first, a page at a time: limit (up to 200, 50 if left out), cursor, start, end, state, model and job, as GET /v1/app/jobs takes them. With no start it goes back to the first job
GET /v1/app/analyticsAPI key only: your whole app's requests over time, with counts of the people signed in to it, never who they are
GET /v1/app/jobsAPI key only: every job of your app, newest first, with no person and nothing they sent or got
GET /files/<name>A file in this app's folder for this person, or one the person picked for it (Range supported)
POST /v1/filesUpload one file of up to 100 MB as the request body, into the app's folder
GET /v1/filesThis app's folder for this person, newest first (limit, cursor, path, bin=1, shared=1)
GET /v1/files/<name>One file's record
PATCH /v1/files/<name>Rename a file (name), move it inside the app's folder (path), or set its labels (app_properties, properties)
DELETE /v1/files/<name>Move a file to the bin
POST /v1/files/<name>/restoreTake it out of the bin
POST /v1/files/<name>/keepKeep a temporary file in the person's Drive without sending it again (optional path)
POST /v1/foldersMake an empty folder inside the app's folder
GET /v1/files/<name>/linkThe file's link anyone can open, or null
POST /v1/files/<name>/linkMake that link (201), or get the one already there (200)
DELETE /v1/files/<name>/linkRemove the link: it stops opening for everyone
GET /v1/storageThe person's space: limit, used, remaining
GET /v1/changes?cursor=What changed among this app's files since the cursor
POST /v1/uploadsStart an upload in parts, for a file over 100 MB
PUT /v1/uploads/<id>/<n>Part n
GET /v1/uploads/<id>Which parts arrived (to resume after a dropped connection)
POST /v1/uploads/<id>/completeFinish it
DELETE /v1/uploads/<id>Cancel it
GET /v1/driveThe whole Drive, Nostrad's own apps only: how much space is used, and each app's folder with the app's name
GET /v1/drive/changes?cursor=What changed anywhere in the Drive since the cursor
GET /v1/drive/changes/wait?cursor=&timeout=Waits until something changes after the cursor, as Dropbox's longpoll does: { "changes": true } as soon as it does, or false after timeout seconds (30 to 480, 30 if left out). Then read the changes with the same cursor
GET /v1/drive/filesOne place or folder (place, app, path, q, type, sort, dir, since, cursor, folder_cursor, limit)
GET /v1/drive/files/<name>One file's record
PATCH /v1/drive/files/<name>Rename it (title), move it (to), or both
DELETE /v1/drive/files/<name>Move it to the Bin
GET /v1/drive/files/<name>/contentIts bytes (Range and HEAD too)
GET /v1/drive/files/<name>/thumbnail?size=A picture's thumbnail: small, medium or large
POST /v1/drive/files/<name>/restoreTake it out of the Bin
POST /v1/drive/foldersMake a folder: { place, app?, path }
PATCH /v1/drive/foldersRename a folder (name) or move it (to)
DELETE /v1/drive/folders?place=&app=&path=Move a folder to the Bin
POST /v1/drive/folders/restoreTake a folder out of the Bin
POST /v1/drive/uploadsStart an upload, or with replaces a new version of a file
PUT /v1/drive/uploads/<id>/<n>Part n
GET /v1/drive/uploads/<id>Which parts arrived
POST /v1/drive/uploads/<id>/completeFinish it
DELETE /v1/drive/uploads/<id>Cancel it
GET /.well-known/nostrad-webhooks.jsonThe public key that signs webhooks and purchase notifications (no token needed)
GET /v1/products?ids=<a,b>Selling: what your app has on sale, with prices (and, for a person's token, what they own)
POST /v1/purchasesStart a purchase for the signed-in person: { product, quantity?, account_token?, return_url }. Answers the Nostrad page to send them to
GET /v1/purchasesWhat the signed-in person owns in your app now (restore)
GET /v1/purchases/voidedYour server: purchases refunded and taken back in the last 30 days
GET /v1/purchases/<token>Your server: one purchase, by its purchase token
POST /v1/purchases/<token>/acknowledgeYour server: say you delivered it, within 3 days, or it is refunded
POST /v1/purchases/<token>/consumeYour server: a consumable is used up, so it can be bought again
POST /v1/purchases/<token>/consumptionYour server: your answer to a refund request
POST /v1/purchases/<token>/cancelYour server: stop a subscription renewing, { "type": "stop_renewals" | "stop_payments" }. Subscriptions
POST /v1/purchases/<token>/revokeYour server: end a subscription now and refund it, { "refund": "full" | "prorated" }. Subscriptions
GET /v1/ordersYour server: your app's orders, newest first, 20 a page
GET /v1/orders/<order_id>Your server: one order, by the order ID the buyer sees
POST /v1/orders/<order_id>/refundYour server: refund an order in full or in part, and take it back or not
POST /v1/notifications/testYour server: send a test notification to your notifications address
GET /v1/notifications/test/<test_token>Your server: whether that test arrived
GET /v1/notificationsYour server: the notifications sent in the last 180 days, and how each went

The selling commands marked "your server" take an API key of the app with Sales ticked; the others take the person's sign-in token. Full guide: Selling inside your app.

Models

curl https://gateway.nostrad.ai/v1/models -H "Authorization: Bearer $TOKEN"
{ "models": [ { "id": "...", "label": "...", "modality": "image",
    "inputs": [ { "key": "prompt", "kind": "text", "required": true } ],
    "params": [ { "key": "aspect_ratio", "kind": "choice", "options": ["1:1", "16:9"], "default": "1:1" } ],
    "price": [ { "unit": "image", "usd": "0.04" } ],
    "available": true } ] }

Prices

To set your own price and show it to your customers, see Charging people for your app. What Nostrad checks before other people can use your app: App review rules.

Each model's price is a list of what one unit costs your caller, in US dollars as a decimal string, so no precision is lost: { "unit": "image", "usd": "0.04" }. It is the price this app's customers pay. price: null means the model has no price yet; unknown never means free, and such a model can't run.

UnitOne unit is
image, image_1k, image_2k, image_4kOne image made (at that size)
edit, extra_input_image, input_imageOne image edit; each input image past the first or past the free ones
input_token, cached_input_token, output_token, video_token…One token (makers quote these per million: multiply by 1,000,000). _long is the long-context price
characterOne character of text spoken
second, second_768p, audio_second, input_video_second_…One second of video or sound made, or of input video
clip_720p_5s_audio and the likeOne whole clip: resolution, length, and with or without sound
song, clipOne song or one clip

A job is charged for what it uses. When it starts, the most it can cost is held from the person's credit (with an API key, yours), and what it didn't use comes back when it ends. The total is rounded up once to a whole cent. A job that fails because of Nostrad costs nothing.

curl https://gateway.nostrad.ai/v1/quote -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" \
  -d '{"model": "<id>", "inputs": {"prompt": "a lighthouse at dawn"}, "params": {"n": 2}}'
{ "model": "<id>", "max_usd": "0.08",
  "lines": [ { "unit": "image", "units": 2, "usd_per_unit": "0.04" } ] }

Checking your limits

GET /v1/key answers for the token you call it with, with the same fields as OpenRouter's key check. Call it before a long task so you don't hit a limit partway through. Amounts are US dollars.

curl https://gateway.nostrad.ai/v1/key -H "Authorization: Bearer $TOKEN"
{ "data": {
  "user_id": "usr_4f1c9a...", "label": "Server key", "via": "key",
  "limit": 100, "limit_reset": "monthly", "limit_remaining": 87.5,
  "usage": 40.2, "usage_daily": 1.1, "usage_weekly": 6.3, "usage_monthly": 12.5,
  "expires_at": null,
  "budgets": [
    { "scope": "api_key", "limit_usd": 100, "spend_usd": 12.5, "remaining_usd": 87.5, "reset_interval": "monthly", "resets_at": "2026-12-01T00:00:00.000Z" },
    { "scope": "account", "limit_usd": 100, "spend_usd": 30, "remaining_usd": 70, "reset_interval": "monthly", "resets_at": "2026-12-01T00:00:00.000Z" }
  ],
  "effective_budget": { "scope": "account", "limit_usd": 100, "spend_usd": 30, "remaining_usd": 70, "reset_interval": "monthly", "resets_at": "2026-12-01T00:00:00.000Z" }
} }

Your app's activity

Two commands show your whole app: the jobs run with your API keys and those of every person signed in to it. They take one of your app's API keys; a person's sign-in token gets 403. The console's Usage and Logs pages show the same.

curl "https://gateway.nostrad.ai/v1/app/analytics?start=2026-11-01&timeframe=day" -H "Authorization: Bearer $NOSTRAD_API_KEY"
{ "app": "...", "start": "2026-11-01T00:00:00.000Z", "end": "2026-11-13T09:00:00.000Z", "timeframe": "day", "via": "all", "model": null,
  "totals": { "request_count": 120, "success_count": 112, "user_error_count": 5, "error_count": 2,
    "p50_prepare_duration": 1, "p75_prepare_duration": 2, "p90_prepare_duration": 4,
    "p50_duration": 31, "p75_duration": 48, "p90_duration": 90, "active_people": 14 },
  "time_series": [ { "bucket": "2026-11-01T00:00:00.000Z", "request_count": 9, ..., "active_people": 6 } ],
  "people": { "shown": true, "minimum": 5, "active": 14, "new": 9, "returning": 5, "active_last_28_days": 17,
    "retention": [ { "day": 1, "people": 9, "returned": 4 }, { "day": 7, "people": 6, "returned": 2 },
                   { "day": 14, "people": null, "returned": null }, { "day": 28, "people": null, "returned": null } ] } }
curl "https://gateway.nostrad.ai/v1/app/jobs?via=signin&state=failed&limit=50" -H "Authorization: Bearer $NOSTRAD_API_KEY"
{ "jobs": [ { "job_id": "job_...", "model": "...", "modality": "image", "via": "signin", "api_key": null, "yours": false,
    "state": "failed", "error": "prompt: is required", "cost_cents": null,
    "prepare_seconds": 1, "duration_seconds": 3, "created_at": 1794563000, "finished_at": 1794563004 } ],
  "next_cursor": "1794562990:job_...", "start": "2026-10-14T09:00:00.000Z", "end": "2026-11-13T09:00:00.000Z" }

5. Running a job

curl https://gateway.nostrad.ai/v1/jobs \
  -H "Authorization: Bearer $TOKEN" \
  -H "content-type: application/json" \
  -d '{"model": "<id from /v1/models>", "inputs": {"prompt": "a lighthouse at dawn"}, "params": {}}'

The answer is the job:

{ "job_id": "job_...", "model": "...", "modality": "image", "state": "done",
  "outputs": [ { "url": "/files/job_..._0.png", "kind": "image", "mime": "image/png", "kept": false } ],
  "error": null, "error_type": null, "retryable": null, "note": null, "usage": { "image": 1 },
  "params": { "aspect_ratio": "1:1" }, "cost_usd": 0.04, "cost_cents": 4,
  "cancel_requested_at": null, "created_at": 1759650000, "finished_at": 1759650012 }

params is the settings the job ran with: yours, with the model's defaults for any you left out. What you sent under inputs (a prompt, files) isn't kept, so it isn't here.

stateMeaning
queued, processingStill running. Ask GET /v1/jobs/<job_id> again every few seconds (video can take minutes). Each read checks the job with the model, at most once every 5 to 10 seconds depending on the model, so asking faster than that answers the same. note may say where it is. GET /v1/jobs lists jobs as last checked; read one job for where it is now.
doneFinished. outputs holds the results; cost_cents (and cost_usd, the same in dollars) is what the person was charged.
failedIt didn't work. error says why (see Errors). Nothing was charged, unless a content check blocked it.

Chat Completions (OpenAI-compatible)

For a chat model, POST https://gateway.nostrad.ai/v1/chat/completions takes and answers OpenAI's Chat Completions, as OpenRouter's does, so an OpenAI client library works with its base address set to https://gateway.nostrad.ai/v1 and your key or the person's token as its API key. It is a chat job underneath: the same price, hold and charge, the same limits, the same Idempotency-Key, and it shows in Logs. The completion's id is the job's ID, and model is the model's ID from GET /v1/models.

curl https://gateway.nostrad.ai/v1/chat/completions \
  -H "authorization: Bearer <token or key>" \
  -H "content-type: application/json" \
  -d '{"model": "<a chat model's id>", "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
       "tools": [{"type": "function", "function": {"name": "weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}}]}'
{ "id": "job_...", "object": "chat.completion", "created": 1759650000, "model": "...",
  "choices": [ { "index": 0, "finish_reason": "tool_calls",
    "message": { "role": "assistant", "content": null,
      "tool_calls": [ { "id": "call_1", "type": "function", "function": { "name": "weather", "arguments": "{\"city\":\"Paris\"}" } } ] } } ],
  "usage": { "prompt_tokens": 50, "completion_tokens": 10, "total_tokens": 60, "prompt_tokens_details": { "cached_tokens": 0 }, "cost": 0.01 } }

Trying again safely

If the connection drops after you send POST /v1/jobs, you can't tell whether the job started, and sending it again would run and charge it twice. To be safe, send a header with a value you make up for this one job, such as a UUID, and send the same value when you try again:

-H "Idempotency-Key: 8f14e45f-ceea-467f-a9f2-1c6a3e0b7d10"

Cancel a job

curl -X POST https://gateway.nostrad.ai/v1/jobs/<job_id>/cancel -H "Authorization: Bearer $TOKEN"
StatusAnswerMeaning
202{ "status": "cancellation_requested" }Asked. A job not started yet is stopped and nothing is charged. A job already running is stopped where the model allows it; otherwise it runs to its end and, if it finishes, is delivered and charged
400{ "status": "already_completed" }The job is already done or failed
404{ "status": "not_found" }No such job for this app and person

A cancelled job ends failed with error: "cancelled by the app" and nothing charged. A job that finished anyway shows cancel_requested_at, the time you asked. Asking again is harmless.

Webhooks: be told when a job ends

Add "webhook": "https://your-server.example.com/nostrad" to POST /v1/jobs. When the job is done or failed, Nostrad POSTs this to that address, usually within a minute:

{ "job_id": "job_...", "app_id": "<your App ID>", "status": "OK",
  "payload": { ...the job, as GET /v1/jobs/<job_id> shows it... },
  "error": null }

Every webhook is signed, so you can check it came from Nostrad and is for your app. It carries four headers:

HeaderWhat it is
X-Nostrad-Webhook-Job-IdThe job's id
X-Nostrad-Webhook-App-IdYour App ID (the console's Overview shows it)
X-Nostrad-Webhook-TimestampWhen it was sent, in seconds since 1970 (UTC)
X-Nostrad-Webhook-SignatureAn Ed25519 signature, in hex

To check it:

  1. Fetch the public key from https://gateway.nostrad.ai/.well-known/nostrad-webhooks.json (a JWKS: { "keys": [ { "kty": "OKP", "crv": "Ed25519", "x": "...", "kid": "..." } ] }). Keep it; fetch it again only when a signature fails.
  2. Refuse the webhook if the App ID isn't yours, or if the timestamp is more than 300 seconds away from your clock.
  3. Build the message: the job id, a newline, the App ID, a newline, the timestamp, a newline, and the SHA-256 of the raw request body as 64 lower-case hex characters.
  4. Check the signature over that message with each key in keys; one must match. Read the body as JSON only after that.
// Checks a Nostrad webhook. Web Crypto only: Cloudflare Workers, Deno, Node 20 or later.
const MY_APP_ID = "<your App ID>";
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
const bytes = (h) => new Uint8Array(h.match(/../g).map((x) => parseInt(x, 16)));
let keys = null, fetchedAt = 0; // the public keys: fetched once, again only when none matches (at most every 5 minutes)

async function verifies(signature, message) {
  for (const k of keys ?? []) {
    const key = await crypto.subtle.importKey("jwk", { kty: k.kty, crv: k.crv, x: k.x }, { name: "Ed25519" }, false, ["verify"]);
    if (await crypto.subtle.verify({ name: "Ed25519" }, key, bytes(signature), message)) return true;
  }
  return false;
}

async function nostradWebhook(request) {
  const jobId = request.headers.get("x-nostrad-webhook-job-id");
  const appId = request.headers.get("x-nostrad-webhook-app-id");
  const timestamp = request.headers.get("x-nostrad-webhook-timestamp");
  const signature = request.headers.get("x-nostrad-webhook-signature");
  const raw = await request.text();
  if (!jobId || appId !== MY_APP_ID || !timestamp || !/^[0-9a-f]{128}$/.test(signature ?? "")) return null;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return null;
  const digest = hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(raw)));
  const message = new TextEncoder().encode(`${jobId}\n${appId}\n${timestamp}\n${digest}`);
  if (!(await verifies(signature, message))) {
    if (Date.now() - fetchedAt < 300_000) return null; // not from Nostrad: answer 400
    fetchedAt = Date.now();
    keys = (await (await fetch("https://gateway.nostrad.ai/.well-known/nostrad-webhooks.json")).json()).keys;
    if (!(await verifies(signature, message))) return null;
  }
  return JSON.parse(raw); // then act only on a job_id your app submitted
}

6. Files and storage

Every Nostrad account has one Drive, which the person opens at https://accounts.nostrad.ai/drive/: Apps (one folder per app), My files (their own files, any kind), Temporary (files passing through, which leave on their own), the Bin, and History (files that have left, with when and why). Every account starts with 1 GB of space. Your app has one place in it: its own folder, Apps / <your app>, holding every file it uploaded or a model made for that person. Your app reads and writes that folder, and the files the person picks for it (the picker), and nothing else.

A program that keeps its own files (settings, notes, saved work)

For a desktop program, a tool or a phone app that signs in to keep its own files in the person's Drive and nothing else, such as settings synced between computers:

  1. In the developer console, Create app. Under Services, untick everything and choose Save.
  2. Under Sign in with Nostrad, Create client of kind Phone, desktop or browser-only (no secret), with the return address http://127.0.0.1/callback. At sign-in any port on it works (RFC 8252 §7.3): listen on a free port of 127.0.0.1 and send http://127.0.0.1:<port>/callback as redirect_uri.
  3. Open the person's own browser (not a window inside your program, RFC 8252 §8.12) at /authorize with PKCE and no scope. The consent page shows your app's name, that it saves files in its own folder, and Continue; there's nothing to tick and no spending limit.
  4. Swap the code for tokens with client_id in the form and no secret, then keep the refresh token where the system keeps passwords (Windows Credential Manager, the macOS Keychain, Android's Keystore). Refresh the same way, with client_id; each refresh gives a new refresh token.
  5. Check GET /v1/storage. While can_keep is false, ask the person to switch on Let <your app> save files to my Drive at https://accounts.nostrad.ai/account#apps: until then what you upload passes through and leaves after 12 hours. Kept files count toward their space (remaining).
  6. Save a file: POST /v1/files with x-keep: true, x-file-name, x-path for its folder (for example skills%2Faudit) and its content-type. Save a new version of it with POST /v1/uploads and replaces plus rev (above), so a change made on another computer meanwhile becomes a conflicted copy instead of being lost.
  7. Find files with GET /v1/files?path=<folder>, or by labels you put on them; read one with GET /files/<name>.
  8. Keep each computer in step with GET /v1/changes and its cursor.
  9. The files are the person's: they see them in their Drive under Apps → your app, and can open, change, move or bin them. Your changes list tells you when they do.

Storage settings

Everything that decides whether a file is kept, who sets it and where.

SettingSet byWhereDefaultWhat it does
keep on a jobyour app, per requestPOST /v1/jobs with "keep": true (the console Playground's Keep the results in my Drive tick sends it)falseAsks to keep the job's results in your folder.
keep_path on a jobyour app, per requestPOST /v1/jobs with "keep_path": "Pictures/Coats""" (the top)The folder inside yours the job's kept results go in, made as they arrive. The job's record says it.
path on an uploadyour app, per requestPOST /v1/uploads with "path"; POST /v1/files with x-path"" (the top)The folder inside yours the upload goes in, made once it is kept.
keep on an uploadyour app, per requestPOST /v1/uploads with "keep": true; POST /v1/files with x-keep: truefalseAsks to keep the upload in your folder.
Let <your app> save files to my Drivethe person, per apptheir account page under Apps → Manage, or the top of your folder in their DriveoffWithout it your keep is ignored and files pass through. GET /v1/storage says it as can_keep. Turning it off keeps the files already kept.
Let <your app> open what's in my filesthe person, per apptheir account page under Apps → Manage, or the top of your folder in their DriveonOff, your app still lists, uploads, moves and bins their files and sees each one's name and size, but not what's in them (below). GET /v1/storage says it as can_open.
Keep (one file)the persona file under Temporary in their Drive-Keeps a file passing through, in your folder, if there is room.
Picked filesthe personthe picker; Stop sharing under Apps → ManagenoneWhich files outside your folder your app may read.
Picker types and maxyour app, per requestthe picker addressevery kind except files that look like programs; 1What the person may pick, and how many.
Free spaceNostrad-1 GB per accountSpace every account gets. Lowering it never deletes files; an account over it keeps its files and can't keep more until it has room.

Set by Nostrad and the same for every app: a temporary result leaves 12 hours after Nostrad has finished sending all of it to your app in one GET (Nostrad can't tell whether your app saved it), or after 7 days if it never does; an upload that isn't kept leaves 12 hours after it arrived; the bin keeps a file 30 days; an unfinished upload lasts 7 days; a file is at most 5 GB.

Upload one file (up to 100 MB)

curl https://gateway.nostrad.ai/v1/files \
  -H "Authorization: Bearer $TOKEN" \
  -H "content-type: image/png" \
  -H "x-file-name: holiday%20photo.png" \
  --data-binary @photo.png

Rename, folders and a file as a job's input

curl -X PATCH https://gateway.nostrad.ai/v1/files/<name> \
  -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" \
  -d '{"name": "holiday 2026.png", "path": "trips/2026"}'

Labels on a file

A file sits in one folder, but your app can keep its own labels on it, such as which characters and which project a picture belongs to, the way Google Drive's custom file properties work. Every file's record has two objects of "key": "value":

The picker: files from the rest of the person's Drive

To use a file the person keeps elsewhere in their Drive, your app lets them choose it in Nostrad's picker, as Google's Drive Picker does: the person sees their Drive, ticks files, and your app gets exactly those. Nothing else of their Drive is ever visible to your app.

  1. Open, in a popup or the system browser (never a web view inside your app), https://accounts.nostrad.ai/pick?client_id=<your client ID>&redirect_uri=<a return address registered on that client>&state=<a value you check on return>. Optional: types=image,video,audio,other (one or more; any also offers files that look like programs; anything else is refused) and max=<how many, 1 or more; 1 if you leave it out>. Only files of those kinds can be picked, and a pick is all the ticked files or none. Each picker page can be answered once, by the account signed in, within 30 minutes; the return address and state are always the ones the page was opened with. The client ID and return addresses are those of Sign in with Nostrad; the person must already have connected your app with it.
  2. The person logs in if needed, sees their places (My files and each app's folder; never the bin or temporary files), searches, ticks files, and chooses Pick or Cancel.
  3. Nostrad sends the browser back to your return address with ?state=<your value>&picked=<name>,<name>, or ?state=...&error=cancel (error=not_connected when the person hasn't connected your app yet). A web app's return page passes the names to the page that opened the picker; a phone or desktop app registers its own return address as it does for sign-in.
  4. Your app then reads each file like its own: GET /v1/files/<name> (with shared: true), GET /files/<name>, or as a job's input; GET /v1/files?shared=1 lists every file picked for it, including files the person picked from a shared space they are in. Your app reads a file from a shared space only while the person still could: they are still in the space, may still download there, and aren't kept out by a folder with limited access; the file isn't in the space's Bin. Otherwise it answers 404. A pick lasts until the person stops sharing the file (under Apps on their account page, or by removing your app's access) or deletes it for good; then it answers 404 and the changes list says unshared with removed: true. A picked file in the person's bin still reads until it is gone for good.

Bigger files, in parts (up to 5 GB)

  1. POST /v1/uploads with { "type": "video/mp4", "size": <bytes>, "name": "clip.mp4" } (optional part_size, a multiple of 4 MiB, default 8 MiB; optional content_hash; optional "keep": true; optional "path", the folder inside yours, as x-path above). The answer gives upload_id, part_size and parts.
  2. PUT /v1/uploads/<upload_id>/<n> for n = 1 to parts, each exactly part_size bytes except the last.
  3. POST /v1/uploads/<upload_id>/complete. The answer (201) is the file's record.
  4. Connection dropped: GET /v1/uploads/<upload_id> lists the missing parts; send only those. An unfinished upload is dropped after 7 days.

Bin, space and keeping in step

As Dropbox's create_shared_link_with_settings, an app can give a file in its own folder a link that anyone can open, with no Nostrad account. It is the same link the person sees under Share in their Drive, so they can remove it there too, and every Drive rule holds.

Sharing your app's files with people

As Google's Drive sharing dialog ("invoked from your app to allow sharing of items on Drive"), your app opens Nostrad's own Share for a file in its folder, and the person chooses who gets it there. Your app never sees who: no email address, name or account reaches it.

  1. Open, in a popup or the system browser (never a web view inside your app), https://accounts.nostrad.ai/share?client_id=<your client ID>&redirect_uri=<a return address registered on that client>&state=<a value you check on return>&file=<name>. The client ID and return addresses are those of Sign in with Nostrad.
  2. The person logs in if needed, and their Drive opens at your app's folder with Share open for the file: people, access (Viewer, Commenter or Editor), an end date and a message, the same dialog as anywhere in their Drive.
  3. When they close it, Nostrad sends the browser back to your return address with ?state=<your value> and nothing else, as Google's dialog tells the app nothing. If it can't open, there is a page saying why with a way back, which returns ?state=...&error=: not_connected (the person hasn't connected your app), insufficient_scope (no scope sharing, as for links), not_found (not a file in your app's folder), not_kept (a temporary file) or in_bin.
  4. Each request can be finished once, by the account it was opened for, within 30 minutes. A request with an unknown client or a return address not registered on it gets a page here and is never sent back.

Someone who doesn't know the person sharing (they have never shared with each other, asked each other for access, or been in the same family, shared space or group) gets the share as a request, as a message request on X or Messenger: it waits in their Requests, and nothing of it opens until they accept. Each person can instead take such shares straight away, or not at all; with the second, Share says it can't share with them and shares nothing. Building a chat or messaging app on this? Your app keeps its own messages and is answerable for them; files sent this way still pass through each person's Requests.

Letting people save files to your folder

As Dropbox's Saver ("the easiest way to add files to your users' Dropboxes", which "opens in a pop-up window"), your app opens Nostrad's own Save window and the person uploads files from their device straight into your app's folder, so your app never holds them on the way.

  1. Open, in a popup or the system browser, https://accounts.nostrad.ai/save?client_id=<your client ID>&redirect_uri=<a registered return address>&state=<your value>, with optional path=<a folder inside your app's folder>. The person must have connected your app with Sign in with Nostrad; no other scope is asked.
  2. Their Drive opens at your app's folder (or that folder) with Save files for <your app> open: Choose files, as many times as they like, then Done, or Cancel. The files are theirs, kept in your folder and counted in their space.
  3. When they close it, Nostrad sends the browser back with ?state=<your value> if anything was saved, as the Saver's success passes nothing, or ?state=...&error=cancel if nothing was, as its cancel. Find the new files with GET /v1/changes or GET /v1/files. If it can't open: error=not_connected.

Showing a file without reading it

Your app opens Nostrad's own viewer for a file in its folder: https://accounts.nostrad.ai/view?client_id=&redirect_uri=&state=&file=<name>, in a popup or the system browser. The person sees the file in their Drive's viewer (pictures, video, sound, PDFs, text and Office files; anything else offers a download), and closing it sends the browser back with ?state=<your value>. Errors as for sharing: not_connected, not_found, in_bin. It is a window rather than a frame in your page: Dropbox's Embedder frames only a shared link, which anyone with the address can open, your app included.

When the person keeps what's in their files from your app

Each person has a switch for your app, Let <your app> open what's in my files, on until they turn it off. Off:

The whole Drive (Nostrad's own apps)

The /v1/drive commands reach everything in a person's Drive, as Google's restricted scope "View and manage all your Drive files" does. Only an app Nostrad has marked can ask for the drive scope: its own sync and phone apps. Your app can't: use your app's folder and the file picker above. An API key never has it, and the token stops carrying it as soon as the person or Nostrad takes it away.

7. Selling inside your app

Sell things inside your app, such as coins, a level or a feature, to people who signed in with Nostrad. They pay from their Nostrad credit on a Nostrad page, as on Google Play or the App Store; you get 70% of the price and Nostrad keeps 30%. It works like Google Play Billing:

  1. Make the products under Monetize in the developer console, and an API key with Sales ticked for your server.
  2. Your app lists them (GET /v1/products) and starts a purchase with the person's token (POST /v1/purchases), then sends their browser to the purchase_url it gets back.
  3. They choose Buy. Nostrad sends their browser back to your return_url with purchase_token added, if that address is one of your sign-in client's return addresses, and tells your server with a signed notification.
  4. Your server checks the purchase (GET /v1/purchases/<token>), delivers it, and acknowledges it within 3 days (POST /v1/purchases/<token>/acknowledge), or consumes a consumable so it can be bought again. A purchase not acknowledged in 3 days is refunded and taken back.

Refunds, refund requests, notifications, test purchases and every field are in Selling inside your app. The API definition is in openapi.json (OpenAPI 3.1).

8. Errors

A refused request answers JSON { "error": "...", "detail": "..." }. error is a code to branch on and is always there: the reason's own (such as over_limit or no_route), or else the status's type: invalid_request_error (400 and any other 4xx below), authentication_error (401), billing_error (402), permission_error (403), not_found_error (404), conflict_error (409), request_too_large (413), rate_limit_error (429), api_error (500, 502, 503) and timeout_error (504). detail is words for a person: don't parse it. New codes may be added.

Every refusal also has an x-should-retry header, true or false: whether sending the same request again can work. It's true for 408, 429 and 5xx, except where the answer keeps failing until something changes (the account's monthly limit, a model with no price yet, a supplier at its limit for the month), and false for everything else. The Retry column below says the same. Wait between tries, longer each time: retry-after seconds when it is given, otherwise 1 second, doubling up to 60.

A job that fails answers the job, with state: "failed", its error (words), error_type and retryable:

error_typeMeaningretryable
invalid_requestSomething in the request the model didn't take; error says whatfalse: fix the request
content_policy_violationThe model's content check blocked it. Charged its listed pricefalse
nostrad_error"Nostrad error": something went wrong on Nostrad's side, not with the request. Nothing was chargedtrue, after a wait

A job read while it is queued, running or done has error_type and retryable null. Job webhooks and GET /v1/app/jobs carry the same two fields. If it fails while it's starting, that answer comes with an error status, 502 when it's Nostrad's fault and otherwise the status in the table below, so a program that stops at any error status has to read the body. The same job read later answers 200. Nothing is charged for a failed job, with one exception: a job blocked by a content check is charged its listed price, the same as a job that finished, and cost_cents shows the amount. To try a failed job again, start it again with a new Idempotency-Key: the same key answers the same failed job.

Every answer, a refusal too, has an x-request-id header (req_ and 24 letters and digits). Keep it with your logs: when you ask about a call that made no job, quote it; for a job, quote its job_id.

StatusMeaningWhat your app doesRetry
400, 409, 413, 415, 422Something in the request: a missing input, a value out of range, too large, a file type not taken, or an Idempotency-Key used before with a different body (idempotency_key_reused). A field that's wrong answers 400 invalid_fields, with metadata.invalid_fields listing each one as { "type", "field", "description" }: type is required, invalid_value or additional_property_not_allowed, and field is where it is, such as params.durationFix the request; detail says what. Branch on type and field, not on the wordsNo
401No token, or it ran out or was taken away; or an API key that is wrong, deleted or expiredRefresh the token; if that fails, sign the person in again. For a key: check it under API keysNo
402Not enough credit. metadata carries limit_source nostrad_credits, scope account and remedy_hint, as OpenRouter's 402 doesTell the person. The error ends with the page where they add it, https://accounts.nostrad.ai/account#credit: show it or link to it. They can also turn on Auto top-up there, so it doesn't happen again. For a key: the same, on your own accountNo
403 (limit)The monthly limit for your app (or for the API key) is reached: error is over_limit, the words end $X of $Y used; resets <time>., and metadata carries limit_source, scope, limit_usd, spend_usd, resets_at and remedy_hint, as OpenRouter's budget errors do (details)For your app's limit, the person changes it under Apps on accounts.nostrad.ai. For a key, raise the key's limit under API keys. Or wait for resets_atNo
403A service the person (or the key) doesn't allow, access taken away, the model refused the content, an API key used from an address it isn't allowed from, a model that needs Sign in with Nostrad, an app that is still personal (only its developer can use it until Nostrad verifies it), or an adult model on an app that doesn't allow adult modelsShow detail to the personNo
403 (age)An app rated 18+, or an adult model, for a person whose Nostrad account doesn't say they're 18 or over: error is age_restricted. For an API key, the key's ownerShow detail: it says where they add their date of birth, under Account details on accounts.nostrad.aiNo
404An unknown model, or something that isn't this app'sCheck the idNo
410A file that has left Nostrad (a temporary file past its hours, or deleted); detail says whyDon't ask againNo
429Too many storage requests, or more than about 600 job starts or 3,000 other requests in a minute for one account, all its keys together (rate_limited)Wait retry-after seconds, longer after each refusalYes
429The account paying already has as many jobs running as it may (this account already has 2 jobs running, the most it can run at once; start this one again when one of them ends; error concurrent_requests_limit, metadata with limit_source nostrad_jobs_at_once and limit). See Jobs at onceStart the job again when one of the running ones ends. Nothing was chargedYes, when one ends
429The account paying has reached its monthly spending limit (this account has reached its monthly spending limit of ...; error account_limit, the same metadata with limit_source nostrad_account_limit)Show detail to the person: it says the limit, the day it comes back and what raises it. It isn't the same as running out of creditNo: it keeps failing until the day in detail
403, 404, 409 (selling)error names the reason, as Google Play does: needs_sign_in, sales_permission_needed, billing_unavailable, unavailable, already_owned, not_owned, already_refunded, refund_too_old, no_refund_request, no_notify_url; 400 developer_error for a request that isn't valid, and invalid_purchase_state for acknowledging a consumed purchaseSee Selling errorsNo
500The Nostrad gateway hit an error of its own (api_error). Nothing was done or chargedTry again later; if it keeps happening, quote the x-request-idYes, after a wait
502"Nostrad error": something went wrong on Nostrad's side, not with the request. Nothing was chargedTry again later, with a new Idempotency-KeyYes, after a wait
503The model is switched off or busy right now (no_route, try_again)Try again later, or another modelYes, after a wait
503The model can't run until Nostrad changes something: no price for it yet (unpriced), your app's price below Nostrad's (price_below_base), or its supplier at Nostrad's limit for the month (route_budget)Use another model. For price_below_base, raise your app's Price under App settingsNo

Getting help

9. Example: a server that signs people in and runs a job

A whole web app in one file, ready to deploy as a Cloudflare Worker: a person signs in with Nostrad, picks an image model, types a prompt and sees the picture, paid from their own Nostrad balance. It uses only fetch, Web Crypto and one KV namespace for its storage (sign-ins in progress and each person's tokens), and it never sends a token to the browser: the browser holds only a random session cookie.

// worker.js: sign people in with Nostrad, then make an image for them.
// Needs: a KV namespace bound as STORE, NOSTRAD_CLIENT_ID (a variable) and NOSTRAD_CLIENT_SECRET (a secret).
const NOSTRAD = {
  issuer: "https://accounts.nostrad.ai",
  authorize: "https://accounts.nostrad.ai/authorize",
  token: "https://accounts.nostrad.ai/oauth/token",
  gateway: "https://gateway.nostrad.ai",
};
const CALLBACK = "/oauth/nostrad/callback"; // registered on the client as https://<your address>/oauth/nostrad/callback
const DAY = 86400;
const b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf)))
  .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const random = (n) => b64url(crypto.getRandomValues(new Uint8Array(n)));
const escape = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => "&#" + c.charCodeAt(0) + ";");
const page = (body, status = 200, headers = {}) => new Response(
  `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>My app</title>${body}`,
  { status, headers: { "content-type": "text/html; charset=utf-8", ...headers } });
const go = (to, headers = {}) => new Response(null, { status: 303, headers: { location: to, ...headers } });
const COOKIE = "; Path=/; HttpOnly; Secure; SameSite=Lax";
class SignInAgain extends Error {}

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const sid = /(?:^|;\s*)sid=([A-Za-z0-9_-]{43})/.exec(request.headers.get("cookie") ?? "")?.[1];
    const session = sid ? await env.STORE.get("session:" + sid, "json") : null;
    try {
      if (url.pathname === "/login") return go(await signInAddress(env, url));
      if (url.pathname === CALLBACK) return await callback(env, url);
      if (url.pathname === "/logout") {
        if (sid) await env.STORE.delete("session:" + sid);
        return go("/", { "set-cookie": "sid=; Max-Age=0" + COOKIE });
      }
      if (!session) return page('<p><a href="/login">Sign in with Nostrad</a></p>');
      const call = (path, init) => gateway(env, sid, session, path, init);
      if (url.pathname === "/") return await home(call);
      if (url.pathname === "/make" && request.method === "POST") return await make(call, await request.formData());
      const job = /^\/jobs\/([A-Za-z0-9_-]{1,100})$/.exec(url.pathname);
      if (job) return await showJob(call, job[1]);
      const file = /^\/jobs\/([A-Za-z0-9_-]{1,100})\/(\d{1,3})$/.exec(url.pathname);
      if (file) return await output(call, file[1], Number(file[2]));
      return page("<p>Not found.</p>", 404);
    } catch (e) {
      if (e instanceof SignInAgain) return go("/login");
      return page(`<p>${escape(e.message)}</p><p><a href="/">Back</a></p>`, 500);
    }
  },
};

// 1. Sign in: keep a code_verifier under a random state for ten minutes, send the browser to Nostrad.
async function signInAddress(env, url) {
  const verifier = random(32), state = random(16);
  const challenge = b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
  await env.STORE.put("flow:" + state, verifier, { expirationTtl: 600 });
  return NOSTRAD.authorize + "?" + new URLSearchParams({
    response_type: "code", client_id: env.NOSTRAD_CLIENT_ID, redirect_uri: url.origin + CALLBACK,
    scope: "image", state, code_challenge: challenge, code_challenge_method: "S256", resource: NOSTRAD.gateway,
  });
}

function tokenCall(env, fields) {
  const basic = btoa(encodeURIComponent(env.NOSTRAD_CLIENT_ID) + ":" + encodeURIComponent(env.NOSTRAD_CLIENT_SECRET));
  return fetch(NOSTRAD.token, {
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded", authorization: "Basic " + basic },
    body: new URLSearchParams(fields),
  }).then(async (r) => { if (!r.ok) throw new Error("Nostrad refused the sign-in (" + r.status + ")"); return r.json(); });
}

// 2. The return address: check state and iss, swap the code for tokens, keep them under a new session.
async function callback(env, url) {
  const q = url.searchParams;
  if (q.get("error")) return page(`<p>Not signed in (${escape(q.get("error"))}).</p><p><a href="/login">Try again</a></p>`, 400);
  if (q.get("iss") !== NOSTRAD.issuer) return page("<p>That sign-in didn't come from Nostrad.</p>", 400);
  const key = "flow:" + q.get("state");
  const verifier = await env.STORE.get(key);
  if (!verifier) return page('<p>That sign-in ran out. <a href="/login">Sign in again</a></p>', 400);
  await env.STORE.delete(key);
  const t = await tokenCall(env, { grant_type: "authorization_code", code: q.get("code"),
    redirect_uri: url.origin + CALLBACK, code_verifier: verifier });
  const sid = random(32);
  await save(env, sid, { user: t.user_id, access: t.access_token, refresh: t.refresh_token, until: Date.now() + t.expires_in * 1000 });
  return go("/", { "set-cookie": `sid=${sid}; Max-Age=${180 * DAY}` + COOKIE });
}
const save = (env, sid, s) => env.STORE.put("session:" + sid, JSON.stringify(s), { expirationTtl: 180 * DAY });

// 3. A gateway call with the person's token: refreshed when it has run out (keeping the new
//    refresh token), and back to sign-in when the sign-in has ended.
async function gateway(env, sid, s, path, init = {}) {
  if (Date.now() > s.until - 60_000) {
    const t = await tokenCall(env, { grant_type: "refresh_token", refresh_token: s.refresh }).catch(() => null);
    if (!t) { await env.STORE.delete("session:" + sid); throw new SignInAgain(); }
    Object.assign(s, { access: t.access_token, refresh: t.refresh_token ?? s.refresh, until: Date.now() + t.expires_in * 1000 });
    await save(env, sid, s);
  }
  const r = await fetch(NOSTRAD.gateway + path, { ...init, headers: { ...init.headers, authorization: "Bearer " + s.access } });
  if (r.status === 401) { await env.STORE.delete("session:" + sid); throw new SignInAgain(); }
  return r;
}

// 4. The page: the image models running now, and a prompt.
async function home(call) {
  const { models } = await (await call("/v1/models")).json();
  const running = models.filter((m) => m.modality === "image" && m.available);
  if (!running.length) return page('<p>No image model is running right now.</p><p><a href="/logout">Sign out</a></p>');
  return page(`<form method="post" action="/make">
    <select name="model">${running.map((m) => `<option value="${escape(m.id)}">${escape(m.label)}</option>`).join("")}</select>
    <input name="prompt" required maxlength="1000" placeholder="a lighthouse at dawn"> <button>Make</button>
  </form><p><a href="/logout">Sign out</a></p>`);
}

// 5. Start the job. A refusal (no credit, a limit) has no job: show its words, which say what to do.
async function make(call, form) {
  const r = await call("/v1/jobs", { method: "POST", headers: { "content-type": "application/json" },
    body: JSON.stringify({ model: form.get("model"), inputs: { prompt: form.get("prompt") } }) });
  const job = await r.json();
  if (!job.job_id) return page(`<p>${escape(job.detail)}</p><p><a href="/">Back</a></p>`, r.status);
  return go("/jobs/" + job.job_id);
}

// 6. The job's page: it reloads itself while the job runs.
async function showJob(call, id) {
  const r = await call("/v1/jobs/" + id);
  if (!r.ok) return page("<p>No such job.</p>", 404);
  const job = await r.json();
  if (job.state === "queued" || job.state === "processing") return page('<meta http-equiv="refresh" content="3"><p>Making it...</p>');
  if (job.state === "failed") return page(`<p>${escape(job.error)}</p><p><a href="/">Back</a></p>`);
  return page(job.outputs.map((o, i) => `<p><img src="/jobs/${id}/${i}" alt="" style="max-width:100%"></p>`).join("") +
    `<p>${job.cost_cents === null ? "" : job.cost_cents + " credits. "}<a href="/">Make another</a></p>`);
}

// 7. A result's bytes, read with the person's token (a result address needs it), passed to the browser.
async function output(call, id, n) {
  const job = await (await call("/v1/jobs/" + id)).json();
  const out = job.outputs?.[n];
  if (!out?.url) return page("<p>Not found.</p>", 404);
  const f = await call(out.url);
  return new Response(f.body, { status: f.status, headers: { "content-type": f.headers.get("content-type") ?? "application/octet-stream",
    "x-content-type-options": "nosniff", "content-security-policy": "sandbox", "cache-control": "private, max-age=3600" } });
}

Its settings file, beside it:

// wrangler.jsonc
{
  "name": "my-nostrad-app",
  "main": "worker.js",
  "compatibility_date": "2026-11-01",
  "vars": { "NOSTRAD_CLIENT_ID": "<your Client ID>" },
  "kv_namespaces": [{ "binding": "STORE", "id": "<the id from step 2>" }]
}

To put it live (you need a Cloudflare account and Node.js):

  1. Save the two files above as worker.js and wrangler.jsonc in a new folder, and open a terminal there.
  2. Run npx wrangler kv namespace create STORE and put the id it prints into wrangler.jsonc.
  3. Run npx wrangler deploy. It prints your app's address, such as https://my-nostrad-app.<your-subdomain>.workers.dev.
  4. In the console, on the Sign in with Nostrad page, choose Create client, then Web server, with the return address https://my-nostrad-app.<your-subdomain>.workers.dev/oauth/nostrad/callback. Put the Client ID into wrangler.jsonc. The client secret is shown once: keep that popup open for the next step.
  5. Run npx wrangler secret put NOSTRAD_CLIENT_SECRET and paste the secret when it asks. It goes into Cloudflare's secret store, never into a file.
  6. Run npx wrangler deploy again, open the address and choose Sign in with Nostrad.

Your app is personal until Nostrad verifies it, so only you can sign in to it at first. The names NOSTRAD_CLIENT_ID, NOSTRAD_CLIENT_SECRET and STORE are only the ones this example reads; use any.

10. Not available yet