Developing a React Native Application Using RapidAPI for AI Image Colorization

I’m currently enrolled in a React Native course that seems a bit old-fashioned. In section nine, the course uses RapidAPI’s AI Picture Colorizer and originally required a base64 encoded image. However, the API has been updated to require image uploads instead. I’m trying to integrate the react-native-image-picker library in my app, but I’m uncertain about how to select an image from the device gallery and upload it according to the new API guidelines. Below is the example code from RapidAPI:

import axios from 'axios';

const formData = new FormData();
formData.append('picture', '');
formData.append('renderQuality', '25');

const config = {
  method: 'POST',
  url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
  headers: {
    'Content-Type': 'multipart/form-data',
    'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
    'x-rapidapi-key': '[YOUR-API-KEY]'
  },
  data: formData
};

axios(config)
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

Here’s what I am currently using:

import React, { Component } from 'react';
import { View, Text, Image } from 'react-native';
import { Button } from 'react-native-elements';
import { ProgressBar } from 'react-native-progress';
import { launchImageLibrary } from 'react-native-image-picker';
import axios from 'axios';

class MyApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      displayMenu: true,
      responseData: null,
      isLoading: true,
      imageBase64: null,
      imageFileName: null,
    };
  }

  selectImageFromGallery() {
    const options = { includeBase64: true };
    launchImageLibrary(options, response => {
      if (response.didCancel) {
        console.log('Image selection canceled');
      } else if (response.error) {
        console.log('Error with image picker');
      } else if (response.customButton) {
        console.log('Custom button pressed');
      } else {
        this.setState({
          imageBase64: response.assets[0].base64,
          imageFileName: response.assets[0].fileName,
        }, () => console.log('Image File Name: ', this.state.imageFileName));
        this.uploadImage();
      }
    });
  }

  uploadImage() {
    const { imageFileName } = this.state;
    const imageData = new FormData();
    imageData.append('picture', imageFileName);
    imageData.append('renderQuality', '10');

    this.setState({ displayMenu: false });
    console.log('Initiating upload');
    axios({
      method: 'POST',
      url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
      headers: {
        'Content-Type': 'multipart/form-data',
        'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
        'x-rapidapi-key': '[YOUR-API-KEY]',
      },
      data: imageData,
    })
    .then(response => {
      this.setState({
        isLoading: false,
        responseData: response.data,
      });
    })
    .catch(error => console.error(error));
  }
}

I’ve contacted the API’s developer for guidance, and they directed me to the RapidAPI documentation, but I’m still facing challenges. I consistently get the error [Error: Request failed with status code 500], and when using the Test Endpoint in RapidAPI, it shows OK, but says “There’s no example response for this endpoint.” Any guidance would be appreciated.

Hi DancingFox,

Analyzing your issue, there are a couple of tweaks necessary to correctly set up your image upload process using the react-native-image-picker and axios. Let's focus on ensuring the FormData contains the correct file format using the URI correctly specified by the image picker.

Currently, you seem to be appending the image file name to the FormData, which won't work since FormData expects a file in a specific structure. Here’s how you can improve it:

1. Ensuring Correct Image Data Retrieval

From the image picker, extract uri, fileName, and type to define the image to upload:

launchImageLibrary(options, response => {
  if (response.didCancel) {
    console.log('Image selection canceled');
  } else if (response.error) {
    console.log('Error with image picker');
  } else {
    const { uri, fileName, type } = response.assets[0];
    const image = {
      uri,
      type,
      name: fileName
    };
    this.setState({
      image
    }, () => {
      console.log('Image selected:', this.state.image);
      this.uploadImage();
    });
  }
});

2. Constructing FormData Object

Modify your uploadImage function to append the image object as it requires the uri, type, and name:

uploadImage() {
  const { image } = this.state;
  const imageData = new FormData();
  imageData.append('picture', image);
  imageData.append('renderQuality', '10');

  console.log('Initiating upload');
  axios({
    method: 'POST',
    url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
    headers: {
      'Content-Type': 'multipart/form-data',
      'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
      'x-rapidapi-key': '[YOUR-API-KEY]',
    },
    data: imageData,
  })
  .then(response => {
    this.setState({
      isLoading: false,
      responseData: response.data,
    });
  })
  .catch(error => console.error('Upload failed:', error));
}

By utilizing the image with the correct properties, you should be able to communicate successfully with the API and resolve the 500 error you've encountered. Adjusting how you construct the FormData is key to submitting your request correctly. Let the community know if this solution solved your problem or if further adjustments are needed!

Hi DancingFox,

It looks like you need to correctly handle the image file before uploading it with the axios request. The main issue you're facing might be related to the content of the FormData being improperly set, particularly how you're appending the image file. Here's an updated approach:

First, ensure you're getting the image URI correctly from the launchImageLibrary method:

launchImageLibrary(options, response => {
  if (response.didCancel) {
    console.log('Image selection canceled');
  } else if (response.error) {
    console.log('Error with image picker');
  } else {
    const { uri, fileName, type } = response.assets[0];
    const image = {
      uri, 
      type, 
      name: fileName
    };
    this.setState({
      image
    }, () => {
      console.log('Image selected:', this.state.image);
      this.uploadImage();
    });
  }
});

Then, in your uploadImage method, make sure to construct the FormData object correctly:

uploadImage() {
  const { image } = this.state;
  const imageData = new FormData();
  imageData.append('picture', image);
  imageData.append('renderQuality', '10');

  console.log('Initiating upload');
  axios({
    method: 'POST',
    url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
    headers: {
      'Content-Type': 'multipart/form-data',
      'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
      'x-rapidapi-key': '[YOUR-API-KEY]',
    },
    data: imageData,
  })
  .then(response => {
    this.setState({
      isLoading: false,
      responseData: response.data,
    });
  })
  .catch(error => console.error('Upload failed:', error));
}

Ensure the image is being properly referenced using its local uri and type as specified by the image picker. This should ideally resolve the 500 error and ensure proper image file uploads according to the current API requirements. Let me know if this helps!