Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Bucephalus-lgtm/6f3f18c53a5e0550449c8c9d638885d4 to your computer and use it in GitHub Desktop.
Save Bucephalus-lgtm/6f3f18c53a5e0550449c8c9d638885d4 to your computer and use it in GitHub Desktop.

Obtain Predictions for Your Replicate API

Within pages/api folder of your root directory for your Next.js app, create a folder called replicate.

Now this looks like: pages/api/replicate, right?

Here, write a file called index.js and then insert the following code:

const getPredictions = async (req, res) => {
  const response = await fetch("https://api.replicate.com/v1/predictions", {
    method: "POST",
    headers: {
      Authorization: "Token <__replicate_API_Token__>",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      version: <__version_of_your_replicate_api__>
      input: { prompt: req.body.prompt },
    }),
  });

  if (response.status !== 201) {
    let error = await response.json();
    res.statusCode = 500;
    res.end(JSON.stringify({ detail: error.detail }));
    return;
  }

  const prediction = await response.json();
  res.statusCode = 201;
  res.end(JSON.stringify(prediction));
  return;
}

export default getPredictions;

Poll the Status of the Prediction by Providing Id

Within pages/api/replicate folder write a file called [id].js

Here, Next.js will take id for dynamic routing and it can be accessed by req.query.id

Now, write the following code in that file:

const getPredictionById = async (req, res) => {
  const response = await fetch(
    "https://api.replicate.com/v1/predictions/" + req.query.id,
    {
      headers: {
        Authorization: "Token <__replicate_API_Token__>",
        "Content-Type": "application/json",
      },
    }
  );
  if (response.status !== 200) {
    let error = await response.json();
    res.statusCode = 500;
    res.end(JSON.stringify({ detail: error.detail }));
    return;
  }

  const prediction = await response.json();
  res.end(JSON.stringify(prediction));
  return;
}

export default getPredictionById;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment