webrakucro

Processing POST request of an audio file


What is the equivalent POST request using:

for this curl shell command:

curl --request POST \
  --url https://api.someservice.com/v1/ \
  --header 'Authorization: Bearer TOKEN' \
  --header 'Content-Type: multipart/form-data' \
  --form file=@/path/to/file/audio.mp3 \
  --form transformer=trans-2 \
  --form format=text

I tried following the examples in "Cro::HTTP::Client" without success...

(See the example starting with my $resp = await Cro::HTTP::Client.post: 'we.love.pand.as/pandas',)


Update

Here is a working example using the answer of @jja that requires to:

use HTTP::Tiny;


my $fileName = $*HOME ~ '/Downloads/HelloRaccoonsEN.mp3';


say .<content>.decode given HTTP::Tiny.post: 'https://api.openai.com/v1/audio/transcriptions',
        headers => { authorization => "Bearer {%*ENV<OPENAI_API_KEY>}" },
        content => {
            file        => $fileName.IO,
            model       => 'whisper-1',
            format      => 'text'
        };

Here is the expected result:

# {"text":"Raku practitioners around the world, eat more onions!"}

Solution

  • This is how that would look with HTTP::Tiny:

    say .<content>.decode given HTTP::Tiny.post: 'https://httpbin.org/anything',
        headers => { authorization => 'Bearer TOKEN' },
        content => {
            file        => 'path/to/your/file'.IO,
            transformer => 'trans-2',
            format      => 'text'
        }
    

    If you set the content to a hash it will default to use a multipart form encoding, and if any of the values supports a slurp method (in this case, the IO::Path you get by calling IO on your path) that will be used to get the value before sending.

    And the output so you can inspect what was sent:

    {
      "args": {}, 
      "data": "", 
      "files": {
        "file": "data:application/octet-stream;base64,...."
      }, 
      "form": {
        "format": "text", 
        "transformer": "trans-2"
      }, 
      "headers": {
        "Authorization": "Bearer TOKEN", 
        "Content-Length": "...", 
        "Content-Type": "multipart/form-data; boundary=\"VfaSnFoNawbxJQnMbtJr\"", 
        "Host": "httpbin.org", 
        "User-Agent": "HTTP::Tiny/0.2.5 Raku", 
        "X-Amzn-Trace-Id": "Root=1-deadbeef-deadbeefdeadbeefdeadbeef"
      }, 
      "json": null, 
      "method": "POST", 
      "origin": "123.45.67.89", 
      "url": "https://httpbin.org/anything"
    }