简体   繁体   中英

curl request in ruby RestClient

The fastbill API states in its docu to make this curl request in order to receive information:

curl -v -X POST \ 
–u {E-Mail-Adresse}:{API-Key} \ 
-H 'Content-Type: application/xml' \ 
-d '{xml body}' \ 
https://my.fastbill.com/api/1.0/api.php

Using RestClient I tried to translate this into a ruby like request:

How I read this: - make a post request to https://my.fastbill.com/api/1.0/api.php using basic authentification and stating the content type in the header, correct?

Now this would be a resource based request in RestClient like this:

First I authenticate:

resource = RestClient::Resource.new( 'https://my.fastbill.com/api/1.0/api.php', 'my@email.de', 'API-KEY-XXXXX' )

which works and authorises me. then putting my request in:

xml = '<?xml version="1.0" encoding="utf-8"?><FBAPI><SERVICE>customer.get</SERVICE><FILTER/></FBAPI>'

resource.post xml, content_type: 'application/xml'

It always returns 400 and I don't know what else to do here.

Also how would json work here?

resource.post param1: 'value', content_type: 'json'

would be obvious.

You can utilize the Restclient::Request.execute. 400 errors typically indicate that the request was not understood by the recipeint. This could be caused by the headers or malformed data. You may need to add the accept header. Try the example below

require 'rest_client'

RestClient::Request.execute(
    method:   :post,
    user:     'api_user@example.com',
    password: 'pass123',
    url:      "https://example/users.json",
    headers:   {content_type: :json, accept: :json},
    payload:  { 'user' => { 'name' => 'John Doe', 'email' => 'john.doe@example.com'} }.to_json,
)

You can find a detailed list of options here

$url="https://my.fastbill.com/api/1.0/api.php";
$curl = curl_init(); 
curl_setopt($curl,CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
print_r(json_decode($result)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM