MovieMinter v2 — Part 2: The API server
In this article series, I will be using LivePeer, Replicate and Replit to create a React-based Decentralized Generative AI Movie NFT Minter. In this article, I will walk through the process of creating a full-stack application capable of making API calls to Replicate and running locally on your desktop.
Building a simple API to run locally using Node.js
There are a number of ways to go about building an application that uses Generative AI APIs on the backend. You can build and deploy a simple API like this on a wide range of services from AWS, Google FireBase, Vercel or others.
In this case, my goal is a very simple project that runs 100% locally on my PC so I can use React as my user interface while running a server to make API calls.
I started by creating a Replit project containing my server under the folder /api/replicate.js with the below code:
import express from "express";
import bodyParser from "body-parser";
import dotenv from "dotenv";
import cors from "cors";
import Replicate from "replicate";
// Load environment variables
dotenv.config();
// Create an express application
const app = express();
// Use CORS middleware
app.use(cors());
// Parse JSON bodies
app.use(bodyParser.json());
// Define the port
const PORT = process.env.PORT || 5001;
// POST route to handle video generation requests
app.post("/generate-video", async (req, res) => {
try {
// Extract prompt and API key from the request body
const { prompt, apiKey } = req.body;
// Initialize Replicate client with the provided API key
const replicate = new Replicate({
auth: apiKey,
});
// Create a prediction using the Replicate client
let prediction = await replicate.deployments.predictions.create(
"rexsaurus", // Replace with your actual deployment name
"movie-minter-v2", // Replace with your actual version
{
input: { prompt },
},
);
// Wait for the prediction to complete
prediction = await replicate.wait(prediction);
// Send the prediction output back to the client
res.status(200).json(prediction.output);
} catch (error) {
console.error("Error generating video:", error);
res.status(500).json({ error: error.message });
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Here I am setting up the necessary endpoint using the Replicate node client. Notice that this server specifically targets my deployment on replicate. This section will need to be modified to match any details you put differently in your deployment:
let prediction = await replicate.deployments.predictions.create(
"rexsaurus", // Replace with your actual deployment name
"movie-minter-v2", // Replace with your actual version
{
input: { prompt },
},
);
This is sufficient for a basic API server running locally that navigates the CORS restrictions to enable us to use a simple web-based UI to call Replicate.