httplib equivalent of curl command

To use ArangoDB from C++ I’m leveraging httplib to interact with the database’s http interface. Example queries like those found in the docs are straight-forward using curl:

curl --user root:test123  --data @- -X POST --dump - http://localhost:8529/_db/Getting-Started/_api/cursor <<EOF
{ "query" : "FOR u IN Airports LIMIT 2 RETURN u", "count" : true, "batchSize" : 2 }
EOF

I’m having difficulty translating the above to C++ code using httplib. As mentioned in the docs the "query" is part of the request body so my best attempt is:

 #include "httplib.h"
 #include <iostream>
 
 int main()
 {
     httplib::Client cli("localhost", 8529);
     cli.set_basic_auth("root", "test123");
 
     httplib::Params params;
     params.emplace(
        "query", 
        "FOR u IN Airports LIMIT 2 RETURN u");
 
     auto res = cli.Post(
         "/_db/Getting-Started/_api/cursor", params);
 
     std::cout << res->status << std::endl;
     std::cout << res->body << std::endl;
}

The above program succeeds with connection and authentication, but the result is:

400
{"code":400,"error":true,"errorMessage":"VPackError error: Expecting digit","errorNum":600}

How can I properly translate the curl command to httplib code?

>Solution :

The issue is with the way you’re passing the query in the request body. Instead of using httplib::Params, you need to send the request body as a string. Here’s the corrected code:

#include "httplib.h"
#include <iostream>
#include <string>

int main()
{
    httplib::Client cli("localhost", 8529);
    cli.set_basic_auth("root", "test123");

    std::string body = "{\"query\":\"FOR u IN Airports LIMIT 2 RETURN u\",\"count\":true,\"batchSize\":2}";
    auto res = cli.Post(
        "/_db/Getting-Started/_api/cursor", body, "application/json");

    std::cout << res->status << std::endl;
    std::cout << res->body << std::endl;
}

Leave a Reply