Node.js Image Generation API: Quick Start Guide

Node.js Image Generation API: Quick Start Guide

How to integrate and save imejisio api response as a file in nodejsHow to Integrate and Save Imejis.io API Response as a File in Node.js

In this tutorial, we will explore how to integrate the Imejis.io API in a Node.js application and save the API response as a file. Imejis.io provides a platform for customizable and interactive designs that can be seamlessly integrated into your projects. By following these steps, you will learn how to make a request to the Imejis.io API and save the response as a file on your local machine using Node.js.

PrerequisitesPrerequisites

Before we proceed with the integration, ensure that you have the following prerequisites:

  1. Node.js installed on your local machine.
  2. A valid API key from Imejis.io. If you don't have one, sign up on their website (https://www.imejis.io) and obtain your API key.
  3. A design ID from Imejis.io. Select or create a design on the Imejis.io platform and make a note of its unique ID.

Let's get started with the integration process:

Note: You can use nested objects, flattened keys with dot notation (e.g., image.opacity, image.borderColor), or combine both formats in a single request for maximum flexibility. You don't have to pass all properties - only send the properties you want to update or change.

const axios = require("axios")
const fs = require("fs")
const path = require("path")
 
const DESIGN_ID = "YOUR_DESIGN_ID"
const YOUR_API_KEY = "YOUR_API_KEY"
 
const createAndSaveFile = async () => {
  // You can combine nested objects and flattened keys in the same request
  let data = JSON.stringify({
    text: {
      text: "Text here",
      color: "#000000",
      backgroundColor: "transparent",
      textBackgroundColor: "transparent",
      borderColor: "transparent",
      strokeColor: "transparent",
    },
    "image.image": "",
    "image.opacity": 1,
    "image.borderColor": "transparent",
  })
 
  let config = {
    method: "post",
    maxBodyLength: Infinity,
    url: `https://render.imejis.io/v1/${DESIGN_ID}`,
    headers: {
      "dma-api-key": YOUR_API_KEY,
      "Content-Type": "application/json",
    },
    data: data,
  }
 
  try {
    const response = await axios({
      ...config,
      responseType: "arraybuffer",
    })
    const filePath = path.join(__dirname, "output.png")
    fs.writeFileSync(filePath, response.data)
    console.log("File saved successfully.")
  } catch (error) {
    console.error("Error integrating Imejis.io API:", error.message)
  }
}
 
createAndSaveFile()

Replace 'YOUR_DESIGN_ID' with the actual design ID you obtained from the Imejis.io platform, and 'YOUR_API_KEY' with your valid API key.

Save the above code in a file named index.js.

To run the integration, open your terminal or command prompt, navigate to the project directory, and execute the following command:

node index.js

If everything is set up correctly, the code will make a POST request to the Imejis.io API with the provided design ID and API key. The API response, which is an image file in this case, will be saved as output.png in the project directory.

That's it! You have successfully integrated the Imejis.io API and saved the response as a file in your Node.js application.

FaqFAQ

What do i need to start generating images with nodejsWhat do I need to start generating images with Node.js?

You need three things: Node.js installed on your machine, an API key from your image generation provider (like Imejis.io), and a design or template ID to render. On the code side, the axios package handles HTTP requests to the API, and the built-in fs module saves the returned image to your file system.

What image formats can an image generation api returnWhat image formats can an image generation API return?

Most image generation APIs return PNG by default because it supports transparency and produces crisp output for graphics with text. Some APIs also support JPEG for smaller file sizes (ideal for photographs) and WebP for optimized web delivery. Check your provider's documentation for supported formats and how to specify them in your request.

Should i use async or sync calls for image generationShould I use async or sync calls for image generation?

Always use async calls with await or .then() promises. Image rendering happens server-side and can take anywhere from a few hundred milliseconds to several seconds depending on complexity. Async requests keep your Node.js application responsive instead of blocking the event loop while waiting for the API to return the rendered image.

How do i handle errors from an image generation api in nodejsHow do I handle errors from an image generation API in Node.js?

Wrap your API call in a try-catch block as shown in the code example above. Check the error response status code to identify the issue: 401 means an invalid API key, 404 means the template wasn't found, and 429 means you've hit rate limits. Log the full error message during development and return user-friendly messages in production.

Are there rate limits on image generation apisAre there rate limits on image generation APIs?

Yes, most image generation APIs enforce rate limits based on your subscription plan. Free tiers typically allow a smaller number of requests per minute, while paid plans offer higher throughput. For production applications, implement retry logic with exponential backoff to handle 429 (Too Many Requests) responses gracefully.