I’m trying to connect my React Native app to an image colorizing API but running into some issues. The API documentation shows it needs a multipart form upload but I can’t get it working with my image picker.
Here’s what the API docs show:
import axios from "axios";
const formData = new FormData();
formData.append("photo", "");
formData.append("quality", "30");
const config = {
method: 'POST',
url: 'https://photo-colorizer-api.p.rapidapi.com/process-image',
headers: {
'content-type': 'multipart/form-data',
'x-rapidapi-host': 'photo-colorizer-api.p.rapidapi.com',
'x-rapidapi-key': '[API-KEY-HERE]'
},
data: formData
};
axios.request(config).then(function (result) {
console.log(result.data);
}).catch(function (err) {
console.error(err);
});
And here’s my React Native code:
import React, {Component} from 'react';
import {View, Text, Image, StyleSheet} from 'react-native';
import {Button} from 'react-native-elements';
import ProgressCircle from 'react-native-progress/Circle';
import {launchImageLibrary} from 'react-native-image-picker';
import axios from 'axios';
export default class PhotoApp extends Component {
constructor(props) {
super(props);
this.state = {
showMenu: true,
resultData: null,
isLoading: true,
imageData: null,
photoName: null,
};
}
selectPhotoFromLibrary() {
const pickerOptions = {
includeBase64: true,
};
launchImageLibrary(pickerOptions, result => {
if (result.didCancel) {
console.log('User cancelled photo selection');
} else if (result.error) {
console.log('Photo picker error occurred');
} else if (result.customButton) {
console.log('User clicked custom button');
} else {
this.setState(
{
imageData: result.assets[0].base64,
photoName: result.assets[0].fileName,
},
() => console.log('photo name: ', this.state.photoName),
);
this.processImage();
}
});
}
processImage() {
const {photoName} = this.state;
const uploadForm = new FormData();
uploadForm.append('photo', photoName);
uploadForm.append('quality', '15');
this.setState({showMenu: false});
console.log('Beginning API request');
axios
.request({
method: 'POST',
url: 'https://photo-colorizer-api.p.rapidapi.com/process-image',
headers: {
'content-type': 'multipart/form-data',
'x-rapidapi-host': 'photo-colorizer-api.p.rapidapi.com',
'x-rapidapi-key': '[API-KEY-HERE]',
},
data: uploadForm,
})
.then(response => {
this.setState({
isLoading: false,
resultData: response.data,
});
})
.catch(error => {
console.error(error);
});
}
...
}
I keep getting a 500 error and I’m not sure what I’m doing wrong. The API test endpoint works fine but gives no example response. Any ideas on how to properly send the image file from the device gallery to this API?