import ballerina/http;
import ballerina/io;

// Creates a new client with the backend URL.
http:Client clientEndpoint = check new ("http://postman-echo.com");

public function main() {
    io:println("GET request:");
    // Sends a `GET` request to the specified endpoint.
    var response = clientEndpoint->get("/get?test=123");
    // Handles the response.
    handleResponse(response);

    io:println("\nPOST request:");
    // Sends a `POST` request to the specified endpoint.
    response = clientEndpoint->post("/post", "POST: Hello World");
    // Handles the response.
    handleResponse(response);

    io:println("\nUse custom HTTP verbs:");
    // Uses the `execute()` remote function for custom HTTP verbs.
    response = clientEndpoint->execute("COPY", "/get", "CUSTOM: Hello World");

    // The `get()`, `head()`, and `options()` have the optional headers parameter to send out headers,
    response = clientEndpoint->get("/get",
                            {"Sample-Name": "http-client-connector"});

    if (response is http:Response) {
        // [Get the content type](https://docs.central.ballerina.io/ballerina/http/latest/classes/Response#getContentType) from the response.
        string contentType = response.getContentType();
        io:println("Content-Type: " + contentType);

        int statusCode = response.statusCode;
        io:println("Status code: " + statusCode.toString());

    } else {
        io:println("Error when calling the backend: ",
                            response.message());
    }
}

//The below function handles the response received from the remote HTTP endpoint.
function handleResponse(http:Response|error response) {
    if (response is http:Response) {
        // [Get the JSON payload](https://docs.central.ballerina.io/ballerina/http/latest/classes/Response#getJsonPayload) from the response.
        var msg = response.getJsonPayload();
        if (msg is json) {
            // Prints the received `JSON` response.
            io:println(msg.toJsonString());
        } else {
            io:println("Invalid payload received:", msg.message());
        }
    } else {
        io:println("Error when calling the backend: ",
                            response.message());
    }
}

Client Endpoint

The HTTP Client Connector can be used to connect to and interact with an HTTP server.

For more information on the underlying module, see the HTTP module.

import ballerina/http;
import ballerina/io;
http:Client clientEndpoint = check new ("http://postman-echo.com");

Creates a new client with the backend URL.

public function main() {
    io:println("GET request:");
    var response = clientEndpoint->get("/get?test=123");

Sends a GET request to the specified endpoint.

    handleResponse(response);

Handles the response.

    io:println("\nPOST request:");
    response = clientEndpoint->post("/post", "POST: Hello World");

Sends a POST request to the specified endpoint.

    handleResponse(response);

Handles the response.

    io:println("\nUse custom HTTP verbs:");
    response = clientEndpoint->execute("COPY", "/get", "CUSTOM: Hello World");

Uses the execute() remote function for custom HTTP verbs.

    response = clientEndpoint->get("/get",
                            {"Sample-Name": "http-client-connector"});

The get(), head(), and options() have the optional headers parameter to send out headers,

    if (response is http:Response) {
        string contentType = response.getContentType();
        io:println("Content-Type: " + contentType);

Get the content type from the response.

        int statusCode = response.statusCode;
        io:println("Status code: " + statusCode.toString());
    } else {
        io:println("Error when calling the backend: ",
                            response.message());
    }
}
function handleResponse(http:Response|error response) {
    if (response is http:Response) {

The below function handles the response received from the remote HTTP endpoint.

        var msg = response.getJsonPayload();
        if (msg is json) {

Get the JSON payload from the response.

            io:println(msg.toJsonString());
        } else {
            io:println("Invalid payload received:", msg.message());
        }
    } else {
        io:println("Error when calling the backend: ",
                            response.message());
    }
}

Prints the received JSON response.

# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `bal run` command below.
bal run http_client_endpoint.bal
GET request:
{"args":{"test":"123"}, "headers":{"x-forwarded-proto":"http", "x-forwarded-port":"80", "host":"postman-echo.com", "x-amzn-trace-id":"Root=1-5f6acc0b-5f17f7991ebad5eb7f01c723", "user-agent":"ballerina"}, "url":"http://postman-echo.com/get?test=123"}
POST request:
{"args":{}, "data":"POST: Hello World", "files":{}, "form":{}, "headers":{"x-forwarded-proto":"http", "x-forwarded-port":"80", "host":"postman-echo.com", "x-amzn-trace-id":"Root=1-5f6acc0b-f81ed9556fbed9f17ee221b9", "content-length":"17", "content-type":"text/plain", "user-agent":"ballerina"}, "json":null, "url":"http://postman-echo.com/post"}
Use custom HTTP verbs:
Content-Type: application/json; charset=utf-8
Status code: 200