How to post JSON data to web service

Recently I have received a question from the user how to send data in JSON format to the web service and I thought that I will post example code here for the others to benefit, so here it is a simple example how to do that.

// use latest version (for raw string support)
Version(7.0);

// Example of formatting JSON string and sending it via InternetPostRequest

// Define the URL for the POST request
// You can use a service like 'https://postman-echo.com/post' for testing
// which simply echoes back the request body and headers.
url = "https://postman-echo.com/post";

// Define some data to be sent in JSON format
_name = "AmiBroker User";
_value = 123.45;
_isActive = True;

// Format the data into a JSON string
// This example assumes simple key-value pairs.
// we use RAW string, so we don't need to escape double quotes
json_data = StrFormat( r'{ "name": "%s", "value": %g, "isActive": %g }', _name, _value, _isActive );

printf("JSON data to send: %s\n", json_data);

// Set a user agent (optional, but good practice)
InternetSetAgent("AmiBroker AFL Client");

// Set the Content-Type header to indicate JSON data
InternetSetHeaders("Content-Type: application/json\r\nAccept: application/json");

// Send the POST request
// The second argument is the data string to be sent in the request body
handle = InternetPostRequest( url, json_data );

if ( handle != 0 )
{
    printf("\nPOST request sent successfully.\n");

    // Get the HTTP status code
    statusCode = InternetGetStatusCode( handle );
    printf("HTTP Status Code: %g\n", statusCode);

    // Read the response from the server
    response = "";
    line = InternetReadString( handle );
    while ( StrLen( line ) > 0 )
    {
        response = response + line;
        line = InternetReadString( handle );
    }

    printf("\nServer Response:\n%s\n", response);

    // Close the Internet handle
    InternetClose( handle );
}
else
{
    printf("\nFailed to send POST request. Error: %s\n", GetLastOSError());
}

// This formula does not plot anything, it's for demonstration of InternetPostRequest
// you can run it from AFL Formula Editor
// and check the output in the "Output" window.

5 Likes

Referring to your older post/reply here:

For AB 7+, would the idea for packing/unpacking JSON data be suitable to pursue now that 'd' - dictionary / map is available to the AFL plugin?

JSON is just a string. You can pass it freely to and from the plugin.

Dictionary type however is new and for internal use only, for as long as internal representation is subject to change. Allowing external use would block innovation/optimization of internal data structures.

1 Like

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.