Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Programatically set POST param using REST::Client module

Tags:

rest

http

post

perl

I've built a REST Server and now I want to rapidly test it from a Perl Client, using REST::Client module.

It works fine if I perform GET Request (explicitly setting parameters in the URL) but I can't figure out how to set those params in POST Requests.

This is how my code looks like:

#!/usr/bin/perl
use strict;
use warnings;

use REST::Client;

my $client = REST::Client->new();

my $request_url =  'http://myHost:6633/my_operation';

$client->POST($request_url); 
print $client->responseContent();

I've tried with something similar to:

$client->addHeader ('my_param' , 'my value');

But it's clearly wrong since I don't want to set an HTTP predefined Header but a request parameter.

Thank you!

like image 451
Javier Alba Avatar asked Sep 03 '10 11:09

Javier Alba


2 Answers

It quite straight forward. However, you need to know what kind of content the server expects. That will typically either be XML or JSON.

F.ex. this works with a server that can understand the JSON in the second parameter, if you tell it what it is in the header in the third parameter.

$client->POST('http://localhost:3000/user/0/', '{ "name": "phluks" }', { "Content-type" => 'application/json'});
like image 85
Phluks Avatar answered Oct 20 '22 00:10

Phluks


The REST module accepts a body content parameter, but I found to make it work with a string of parameters, you need to set a proper content type.

So the following code works for me:

$params = $client->buildQuery([username => $args{username},
             password => $args{password}]);

$ret = $client->POST('api/rest/0.001/login', substr($params, 1), 
           {'Content-type' => 'application/x-www-form-urlencoded'});
like image 27
Stefan Hornburg Avatar answered Oct 19 '22 22:10

Stefan Hornburg