Talk to REST API

Hi All,

wasn’t here for quite a while but now I am working on a new project where I have to talk to the REST API. I read something in the forum that the URL class now supports PUT, GET etc. but this stuff is totally new to me. Therefore I ask whether there is somebody who would be willing to give a short example code snippet to send a PUT/GET statement or point me into the right direction.

Thank you in advance

I believe you use the url class in conjunction with the input/output stream classes.

something like :

InputStream* io = url.createInputStream (true);

for a get request…

Not certain though.

From the JUCE Demo example project, NetworkingDemo.cpp

String getResultText (const URL& url)
    StringPairArray responseHeaders;
    int statusCode = 0;

    ScopedPointer<InputStream> stream (url.createInputStream (false, nullptr, nullptr, String(),
                                                              10000, // timeout in millisecs
                                                              &responseHeaders, &statusCode));
    if (stream != nullptr)
        return (statusCode != 0 ? "Status code: " + String (statusCode) + newLine : String())
                + "Response headers: " + newLine
                + responseHeaders.getDescription() + newLine
                + "----------------------------------------------------" + newLine
                + stream->readEntireStreamAsString();

    if (statusCode != 0)
        return "Failed to connect, status code = " + String (statusCode);

    return "Failed to connect!";

This is for the GET. If you need to POST or PUT, use either URL::withPOSTData() or URL::withDataToUpload().

Hope that this points you in the right direction.

Happy coding !

I created a module for this purpose, tried to make the API nice and straightforward to use:

I designed it to allow method chaining so for example you can call it like this:

adamski::RestRequest::Response response = request.put ("_users/" + id)
        .field ("type", "user")
        .field ("name", username)
        .field ("email", email)
        .field ("roles", Array<var>({var("publisher")}))

Feel free to create any issues or PR’s via Github if you come across any bugs or could see improvements!

EDIT: I need to update it to the JUCE 4.2 module format which I will do over the next few days when I get a chance. (If you have the inclination to create a PR for this I’d be grateful!)

1 Like

Hi there,

thank you very much for all your input. It really helped me, especially the module class from adamski.
Really nice and working of the shelf. Could get my task working with no hassle.

Thank you again!


1 Like