Search code examples
perllwp

Using variable for HTTP request headers with Perl


I am trying to write a function to create HTTP requests (POST and GET mostly) in Perl. I am keeping everything generic by using variables so that I don't have to worry about the type of request, the payload, headers, etc, however HTTP::Request->header() doesn't seem to like my variable:

    my($req_type, $headers, $endpoint, $args, $request, $jsonfile) = @_;
    my $ua = LWP::UserAgent->new;
    my $req = HTTP::Request->new($req_type => $endpoint);
    $req->content_type('application/json');

    foreach (@$headers) {
        $req->push_header($_);
    }

    $req->content($args);
    $req->content($request);

    print "request : ".$req->as_string;

I tried a few different approches, and using push_header got me the closest, but I realize it may not be the best solution. I think it might have something to do with single quotes getting passed in:

@headers = "'x-auth-token' => '$_token'";

I can post more of the code if it is helpful. I'm hoping some Perl guru will know exactly what I'm doing wrong. I'm sure it's something to do with the format of the string I'm passing in.


Solution

  • @headers = "'x-auth-token' => '$_token'";

    The header function expects to be passed two arguments. The header name and the header value.

    You are passing it one argument: a string containing a fragment of Perl code.

    You need to format your data more sensibly.


    my %headers = (
        "x-auth-token" => $_token;
    );
    

    and

    foreach my $header_name (keys %headers) {
        $req->push_header($header_name => $headers{$header_name});
    }