← Code Recipes
Image & Video

Replicate Free code examples in Python and JavaScript

Thousands of community models behind one API, billed per second.

C# Python Java JavaScript

WHAT THIS PAGE COVERS

Running any model on the platform from one generic client.

Model black-forest-labs/flux-schnell
Package replicate
Checked

Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.

Install

The token is REPLICATE_API_TOKEN — a token rather than a key, and the client reads it from the environment with no arguments.

pip install replicate

export REPLICATE_API_TOKEN="r8_your-token"   # macOS / Linux
setx REPLICATE_API_TOKEN "r8_your-token"     # Windows, then open a new shell
Run any model

One call, one model reference. Billing is per second of compute, so a cold start on a rarely used model costs more than the same run on a warm one — worth knowing before benchmarking two models against each other.

import replicate

output = replicate.run(
    "black-forest-labs/flux-schnell",
    input={"prompt": "astronaut riding a rocket like a horse"},
)

# output is a list of FileOutput objects, not URLs.
with open("output.png", "wb") as handle:
    handle.write(output[0].read())
What FileOutput actually is

It is a stream, not a string. Printing it gives a URL that expires; iterating it gives chunks. For anything large, stream rather than calling .read() and holding the whole file in memory.

output = replicate.run(
    "black-forest-labs/flux-schnell",
    input={"prompt": "a 19th century portrait of a raccoon gentleman"},
)

# Small files: read it all.
data = output[0].read()

# Large files — video especially — stream it instead.
with open("large.mp4", "wb") as handle:
    for chunk in output[0]:
        handle.write(chunk)
Swapping models without changing the client

THIS IS THE REASON TO BE HERE. The client, the auth and the response handling are identical; only the reference and the input keys move. Each model documents its own input schema on its page.

JOBS = [
    ("black-forest-labs/flux-schnell",
     {"prompt": "a brass microphone on a dark desk"}),

    ("stability-ai/sdxl",
     {"prompt": "a brass microphone on a dark desk", "width": 1024}),
]

for reference, payload in JOBS:
    output = replicate.run(reference, input=payload)

    # Some models return a list, some a single FileOutput. Normalise.
    files = output if isinstance(output, list) else [output]

    for index, file in enumerate(files):
        name = reference.replace("/", "-")
        with open(f"{name}-{index}.png", "wb") as handle:
            handle.write(file.read())
Not blocking on a slow model

replicate.run() waits, and a video model can take minutes. predictions.create returns immediately and a webhook tells you when it is done — the same shape as every other async media API on this site.

prediction = replicate.predictions.create(
    model="black-forest-labs/flux-schnell",
    input={"prompt": "Watercolor painting of an underwater submarine"},
    webhook="https://example.com/your-webhook",
    webhook_events_filter=["completed"],
)

print(prediction.id, prediction.status)

# Without a webhook, reload() refreshes it in place and wait() blocks.
# Prefer the webhook: polling a per-second-billed platform adds
# requests without making anything finish sooner.
Install

Same package name as Python. The constructor reads REPLICATE_API_TOKEN, so nothing about the token appears in code.

npm install replicate

export REPLICATE_API_TOKEN="r8_your-token"
Run any model

A model reference can be owner/name, or owner/name:version pinned to an exact build. PIN IT IN PRODUCTION — an unpinned reference follows the model's latest version, and community models change without warning.

import { writeFile } from "node:fs/promises";
import Replicate from "replicate";

const replicate = new Replicate();

const [output] = await replicate.run(
  "black-forest-labs/flux-schnell",
  { input: { prompt: "astronaut riding a rocket like a horse" } },
);

// FileOutput is a ReadableStream; writeFile accepts it directly.
await writeFile("output.png", output);
Swapping models without changing the client

The client, the auth and the output handling stay put. Only the reference and the input keys change — which is the whole argument for routing through Replicate rather than integrating four vendors.

const JOBS = [
  ["black-forest-labs/flux-schnell",
   { prompt: "a brass microphone on a dark desk" }],

  ["stability-ai/sdxl",
   { prompt: "a brass microphone on a dark desk", width: 1024 }],
];

for (const [reference, input] of JOBS) {
  const result = await replicate.run(reference, { input });

  // Some models return an array, some a single FileOutput.
  const files = Array.isArray(result) ? result : [result];

  await Promise.all(
    files.map((file, index) =>
      writeFile(`${reference.replace("/", "-")}-${index}.png`, file),
    ),
  );
}
Not blocking on a slow model

run() waits for the whole prediction, which for a video model is minutes. predictions.create returns straight away and posts to your webhook when it completes.

const prediction = await replicate.predictions.create({
  model: "black-forest-labs/flux-schnell",
  input: { prompt: "painting of a cat by andy warhol" },
  webhook: "https://my.app/webhooks/replicate",
  webhook_events_filter: ["completed"],
});

console.log(prediction.id, prediction.status);
Handling the callback

The body is the full prediction. Check status before reading output — a failed prediction has an error and no output, and a webhook fires for both.

import express from "express";

const app = express();
app.use(express.json());

app.post("/webhooks/replicate", async (request, response) => {
  const { id, status, output, error } = request.body;

  if (status !== "succeeded") {
    console.error(`prediction ${id} ${status}: ${error ?? "no detail"}`);
    return response.sendStatus(204);
  }

  // output here is plain URLs, not FileOutput — this is a fresh
  // HTTP request, not the SDK. Download them before they expire.
  const urls = Array.isArray(output) ? output : [output];
  for (const [index, url] of urls.entries()) {
    const file = await fetch(url);
    await writeFile(`${id}-${index}.png`,
      Buffer.from(await file.arrayBuffer()));
  }

  response.sendStatus(200);
});

app.listen(3000);

QUESTIONS

Which languages are the Replicate examples in?

Python and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.

Which package do I install for Replicate?

The samples use replicate. The install step on each language tab gives the exact command.

Which Replicate model do these examples use?

black-forest-labs/flux-schnell, checked against the official documentation on 26 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.

Where is the official Replicate documentation?

https://replicate.com/docs — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.

ALSO IN IMAGE & VIDEO

The authority

Official Replicate documentation

Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.

Read the docs ↗

https://replicate.com/docs

New drops, every week

Free tools & Claude templates, landing regularly.

We keep shipping new free tools, code recipes and Claude Code templates. Follow @freeyantra on Instagram or join the newsletter so you never miss one.

Follow @freeyantra

or get them by email

Double opt-in. Unsubscribe any time. Privacy