Cristobal BL
Cristobal BL

Reputation: 135

POST an audio file to an API endpoint with Javascript

I'm trying to POST a file already stored in the mobile device to this 3P shazam API to recognize the song. But I'm getting this error code:

{“detail”:[{“loc”:[“body”,“file”],“msg”:“field required”,“type”:“value_error.missing”}]}

API: https://rapidapi.com/tipsters/api/shazam-core

Endpoint: /v1/tracks/recognize

This is the info needed by the endpoint:

enter image description here

And this is how I'm trying the request.

let audioFile = new File([""], fileUri, {type: "audio/wav"});

  const data = new FormData();
  data.append('file', audioFile);

  const options = {
    method: 'POST',
    headers: {
      'X-RapidAPI-Key': 'MY_API_KEY',
      'X-RapidAPI-Host': 'shazam-core.p.rapidapi.com',
      'Content-Type': 'application/octet-stream'
    },
    body: data
  };

  try {
    const response = await fetch(url, options);
    console.log(response.status);
    const result = await response.text();
    console.log(result);
    return result;
  } catch (error) {
    console.error(error);
  }

Any other idea on how to make the call and send the audio file with JS?

Upvotes: 1

Views: 1374

Answers (1)

Cristobal BL
Cristobal BL

Reputation: 135

I solved it by using the uploadAsync method from expo-file-system

  1. npm install expo-file-system
  2. import * as FileSystem from 'expo-file-system';
  3. Posting the file
    const response = await FileSystem.uploadAsync(url, audioFileUri, {
      fieldName: 'file',
      httpMethod: 'POST',
      uploadType: FileSystem.FileSystemUploadType.MULTIPART,
      headers: {
        'X-RapidAPI-Key': apiKey,
        'X-RapidAPI-Host': 'shazam-core.p.rapidapi.com',
      }
    });

Upvotes: 1

Related Questions