1

Am trying to parse curl api

but am getting this error 401 Unauthorized

i don't know where is the problem comes from.

because the authentication details are ok

this is the curl

curl 'https://api.twilio.com/2010-04-01/Accounts/SID/Messages.json' \
   -X POST \
   --data-urlencode 'To=whatsapp:+123456789' \
   --data-urlencode 'From=whatsapp:+1234567890' \
   --data-urlencode 'Body=Your Yummy Cupcakes Company order of 1 dozen frosted cupcakes has shipped and should be delivered on July 10, 2019. Details: http://www.yummycupcakes.com/' \
   -u SID:[AuthToken]
#!/usr/bin/perl

use strict;
use warnings;
use HTTP::Tiny;
use JSON;
use Data::Dumper;

my $url = "https://api.twilio.com/2010-04-01/Accounts/SID/Messages.json";
my $json = encode_json {
To    => 'whatsapp:+256775562361',
From => 'whatsapp:+14155238886',
Body   => 'new test msg',
};

my $http = HTTP::Tiny->new(
default_headers => {
Authorization => 'SID:TOKEN',
}
);

my $response = $http->post( $url => {
content => $json,
headers => { 'Content-Type' => 'application/json' },
});

if ( $response->{'is_success'} ) {
print Dumper( decode_json $response->{'content'} );
} else {
print "$response->{'status'} $response->{'reason'}\n";
}
3
  • Re "but am getting this error", What error? Commented Mar 22, 2022 at 16:12
  • Re "this is the curl", Are you saying this version works? So why are you sending JSON in the Perl version? Commented Mar 22, 2022 at 16:13
  • 401 Unauthorized Commented Mar 22, 2022 at 16:39

1 Answer 1

1

The format of the "Authorization" header isn't <user>:<pass> -- it's <auth-scheme> <authorization-parameters>. curl is doing this for you, but for this it's basically:

Authorization: Basic <mime-encoded "<user>:<pass>">

I use the URI module for this:

my $uri = URI->new("https://api.twilio.com/...");
$uri->userinfo("$sid:$auth");

$http->post( $uri => ... );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.