Rick
Rick

Reputation: 45

Sending audio file to api with python

I am running into a problem with sending an audiofile to my API.

Front:

import requests
url = "https://f16de73c.ngrok.io/api/audio"
files = {'command': open(r'C:\Users\rickk\Desktop\agenda.wav', 'rb')}

headers = {
  'content-type': 'multipart/form-data'
}
r = requests.post(url, files=files, headers=headers)
print(r)
print(r.text)

When I send an API call to my backend without the header, the backend will receive the file but it will return a 400 because it has no content type. When I add a header I will receive a status code of 500 back

'content-type': 'audio/wav' also give me a status code 500 back

Backend:

    [Produces("application/json")]
    [Route("api/audio")]
    [HttpPost]
    public async Task<IActionResult> ProcessCommandAsync([FromForm]IFormFile command)
    {  
        if(command.ContentType != "audio/wav" && command.ContentType != "audio/wave" || command.Length < 1)
        {
            return BadRequest();
        }
        var text = await CovnvertSpeechToTextApiCall(ConvertToByteArrayContent(command));

        return Ok(FormulateResponse(text));
    }

When i send a request with Postman/Insomnia without any headers no problem so i created some code with postman it. The backend accepts it and the sees the content type as audio/wav but the file is obviously empty.

import requests

url = "http://localhost:57566/api/audio"

payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"command\"; filename=\"agenda.wav\"\r\nContent-Type: audio/x-wav\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
}

response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)

Does anyone know/has any suggestions as to how to send the audio file to the backend with the right content-type?

Upvotes: 0

Views: 14225

Answers (2)

annish kumar
annish kumar

Reputation: 23

I was facing the similar problem. below code worked for me

import requests

url = " https://ba7928ba.ngrok.io/api/audio"
fin = open(r'D:/MediaFiles/OneDrive_1_2-7-2020/Recording_90.wav', 'rb')
files = {'file': fin}
r = requests.post(url, files=files)
print(r)
print(r.text)

Upvotes: 0

user9455968
user9455968

Reputation:

Don't use files, which sends a multipart request with named parts, but use data which sends the raw audio file as the request body. Set the content-type to audio/wav:

import requests

url = "https://f16de73c.ngrok.io/api/audio"
data = open(r'C:\Users\rickk\Desktop\agenda.wav', 'rb')}   
headers = {'content-type': 'audio/wav'}

r = requests.post(url, data=data, headers=headers)

print(r)
print(r.text)    

Upvotes: 3

Related Questions