3

I am trying to upload .apk / .ipa file to browserstack cloud programmatically (instead of running the curl command)

Option 1: Node-fetch api

const myfetch = require('node-fetch');

const buildToPost = {
   file: '</my path>'
};

const options = {
   method: 'POST',
   body: JSON.stringify(buildToPost)
};

myfetch('https://</myusername>:</mykey>@api.browserstack.com/app-automate/upload', options)
   .then(res => res.json())
   .then(res => console.log(res))
   .catch(error => console.error('Error:', error));​

But its giving following error:

{ error: 'Invalid format. Refer to REST API document for valid API format - https://www.browserstack.com/app-automate/rest-api' }

Option 2: Axios API

    const axios = require('axios');

axios.post('https://</myusername>:</mykey>​@api-cloud.browserstack.com/app-automate/upload', {
      File: '</my path>​'
   })
   .then
   ((response) => {
      console.log(response);
   }).catch((error) => {
      console.log((error));
})​

Error: data:

{ error: 'Invalid format. Refer to REST API document for valid API format - https://www.browserstack.com/app-automate/rest-api' } } }

Curl command reference:

curl -u "</myusername>:</mykey>" -X POST https://api-cloud.browserstack.com/app-automate/upload -F "file=@/path/to/app/file/Application-debug.apk" -F 'data={"custom_id": "MyApp"}'

Browserstack sample link

James Z
  • 11,838
  • 10
  • 25
  • 41
user2451016
  • 1,204
  • 2
  • 15
  • 30

1 Answers1

1

Here's how to do it with axios. The important points are:

  • Authentication (using the user option)
  • Use of the FormData module to submit multipart data
  • Setting the maxContentLength option high enough to allow your file to be uploaded.

Code below.

import axios from 'axios';
import fs from 'fs';
import FormData from 'form-data';

const formData = new FormData();

// Open file stream
const newFile = fs.createReadStream(binaryPath);

// Add form field params
formData.append('file', newFile, 'my_filename.apk');
formData.append('custom_id', 'npm_uploaded_apk');

axios({
  url: 'https://api-cloud.browserstack.com/app-automate/upload',
  method: 'post',
  headers: formData.getHeaders(),
  auth: {
    username:'my_browserstack_username',
    password: 'my_browserstack_access_key',
  },
  data: formData,
  maxContentLength: 1073741824,
})
  .then(response => {
    // The object with the 'app_url' parameter is in the 'data' field of the response.
    console.log('POST successful: ', response.data);
  })
  .catch((error) => {
    console.log('POST error: ', error);
  });

More background on this in this GitHub thread.

Mike Cavaliere
  • 517
  • 5
  • 8