How to make a RESTful API call using Splashkit

Written by Cyrill Illi on Oct 3 2018

In the world of web services and microservices many companies make their data availlable through a REST API, like twitter, google, weather channels, stock market movement etc. This allows 3rd party software to utilize this data within their own application with a simple API call. In this document we want to use the Networking and JSON Splashkit Library functions to make a RESTful API call.

REST is an acronym for REpresentational State Transfer which means a client’s API call will be answered with a representation of the requested resources state. For example if I were to request data for a particular stock market company I might get the name of the company, the abbreviation on the market, the share value, and whether it has gone up or down since the last refresh. This data represents the state of the resource.

In order to make a HTTP REST call two parameters must be passed along, one the resource that is requested which is embedded in the URL, and two, the operation you want to perform like GET, POST, PUT, DELETE. The Splashkit network library supports the first two.

A REST request data transfer can be in a JSON format, but other formats such as XML or HTTP are possible and often multiple formats are supported by a RESTful API server. In this document we are using the JSON format to represent both the data we send and receive. Which format we wish to use for the transfer is defined in the header of the HTTP request see example 3.

Test JSON Server

The following code examples make use of the JSONPlaceholder to test the code. In the examples we use the /posts resource which contain 100 posts. Each post contains the following elements:

  • id
  • userId
  • title
  • body

Example 1: GET Resource

In this first example we make use of a simple GET operation to retrieve a single resource from an REST API server. The URL tells us which resource to request, in this case it’s the 1st post. The response is converted to a string and the the HTTP response must be set free. The string now contains the JSON response, but to call the key value pairs in the string it must be converted to a JSON object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "splashkit.h"
#include <string.h>

using namespace std;

int main()
{
    http_response get_data;
    string response;

    // Get a single JSON web resource
    get_data = http_get("https://jsonplaceholder.typicode.com/posts/1", 443);
    response = http_response_to_string(get_data);
    free_response(get_data);
    // Output the response
    json json_response = json_from_string(response);
    write_line("UserID => " + to_string(json_read_number_as_int(json_response, "userId")));
    write_line("ID     => " + to_string(json_read_number_as_int(json_response, "id")));
    write_line("Title  => " + json_read_string(json_response, "title"));
    write_line("Body   => " + json_read_string(json_response, "body"));
    write_line("================");

    return 0;
}
1
2
3
4
5
6
7
8
9
import requests

# Get a single JSON web resource
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')

# Output the response
if response.status_code == 200:
  for key, value in response.json().items():
    print("{0} => {1}".format(key, value))

Example 2: GET Resources

Once more we use the GET operator, but this time we request all the post. The response string now contains 100 posts. In order to convert them we would need to split the string into a vector and convert each response to a JSON object. This is not done in the example since the Splashkit has no split function instead we output the string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "splashkit.h"
#include <string.h>

using namespace std;

int main()
{
    http_response get_data;
    string response;

    // Get a list of a JSON web resource
    get_data = http_get("https://jsonplaceholder.typicode.com/posts/", 443);
    response = http_response_to_string(get_data);
    free_response(get_data);
    // To access each JSON key value pair the string should be split to an vector<json>
    // objects for simplicity sake we output just the string here.
    write_line(response);

    return 0;
}
1
2
3
4
5
6
7
8
9
10
import requests

# Get a list of JSON web resources
response = requests.get('https://jsonplaceholder.typicode.com/posts/')

# Output the response
if response.status_code == 200:
  for i in response.json():
    for key, value in i.items():
      print("{0} => {1}".format(key, value))

Example 3: POST Resource

In this example we create a resource on the remote server by using the POST operation. This request requires the header definition specified the content type and the charset. This header must be within a vector as specified in the Splashkit documentation. The data is formed as a JSON object that is converted to a string for the purpose of the HTTP request. Note that the body only contains three parameters as the id is generated on the server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "splashkit.h"
#include <string.h>

using namespace std;

int main()
{
    http_response get_data;
    string response;

    // Create a JSON Web resource
    // Create the JSON body for the http post call
    json body = create_json();
    json_set_string(body, "title", "foo");
    json_set_string(body, "body", "test entry");
    json_set_number(body, "userId", 1);
    // Create the header for the http post call
    vector<string> headers;
    headers.push_back("Content-type: application/json; charset=UTF-8");
    // Send the request
    get_data = http_post("https://jsonplaceholder.typicode.com/posts", 443, json_to_string(body), headers);
    response = http_response_to_string(get_data);
    free_response(get_data);
    // Output the response
    json json_response = json_from_string(response);
    write_line("Following resource has been created");
    write_line("UserID => " + to_string(json_read_number_as_int(json_response, "userId")));
    write_line("ID     => " + to_string(json_read_number_as_int(json_response, "id")));
    write_line("Title  => " + json_read_string(json_response, "title"));
    write_line("Body   => " + json_read_string(json_response, "body"));
    write_line("================");

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import requests

url = 'https://jsonplaceholder.typicode.com/posts/'
# Create the JSON body for the http post call
body = {
  'title':'foo',
  'body':'Test Entry',
  'userId':1
  }
# Create a JSON Web resource
response = requests.post(url, json=body)

# Output the response
if response.status_code == 201:
  for key, value in response.json().items():
    print("{0} => {1}".format(key, value))