Skip to main content

Actions

The ballerina/http package exposes the following clients:

ClientPurpose
ClientStandard HTTP client for outbound requests with full protocol support, resilience, and auth.
StatusCodeClientHTTP client with status-code-based typed response binding.
FailoverClientAttempts subsequent endpoints on failure for high availability.
LoadBalanceClientRound-robin load balancing across multiple endpoints.

Client

Standard HTTP client for making outbound requests to HTTP and HTTP2 endpoints. Supports connection pooling, circuit breaking, retry, caching, compression, and authentication.

Configuration

FieldTypeDefaultDescription
httpVersionHttpVersionHTTP_2_0HTTP protocol version (HTTP_1_0, HTTP_1_1, HTTP_2_0).
http1SettingsClientHttp1Settings{}HTTP/1.x specific settings (keep-alive, chunking, proxy).
http2SettingsClientHttp2Settings{}HTTP/2 specific settings (prior knowledge, window size).
timeoutdecimal30Request timeout in seconds.
poolConfigPoolConfiguration()Connection pool configuration (max active/idle connections, wait time).
authClientAuthConfig()Authentication configuration (Basic, Bearer, JWT, OAuth2).
retryConfigRetryConfig()Retry policy (max retries, interval, backoff factor).
circuitBreakerCircuitBreakerConfig()Circuit breaker configuration (failure threshold, wait duration).
cacheCacheConfig{}HTTP response caching configuration.
compressionCompressionCOMPRESSION_AUTOCompression behavior (COMPRESSION_AUTO, COMPRESSION_ALWAYS, COMPRESSION_NEVER).
followRedirectsFollowRedirects()Redirect following configuration (enabled, max count).
cookieConfigCookieConfig()Cookie handling configuration.
responseLimitsResponseLimitConfigs{}Response size limits (max header size, max body size).
secureSocketClientSecureSocket()TLS/SSL configuration (certificates, protocol, validation).
proxyProxyConfig()HTTP proxy configuration (host, port, credentials).
validationbooleantrueEnable/disable payload validation.
laxDataBindingbooleanfalseEnable lenient data binding for response payloads.

Initializing the client

import ballerina/http;

http:Client httpClient = check new ("https://api.example.com");

With retry and circuit breaker:

import ballerina/http;

http:Client httpClient = check new ("https://api.example.com", {
timeout: 30,
retryConfig: {
count: 3,
interval: 1,
backOffFactor: 2.0,
maxWaitInterval: 20
},
circuitBreaker: {
rollingWindow: {timeWindow: 60, bucketSize: 10},
failureThreshold: 0.5,
resetTime: 30
}
});

Operations

HTTP requests

get

Sends an HTTP GET request to the specified path.

Parameters:

NameTypeRequiredDescription
pathstringYesRequest path.
headersmap<string|string[]>?NoOptional HTTP headers. Defaults to ().
targetTypeTargetTypeNoExpected return type for automatic data binding. Inferred from the call site when omitted.

Returns: targetType|ClientError

Sample code:

// Get raw response
http:Response response = check httpClient->get("/api/users");

// Get with payload binding
json users = check httpClient->get("/api/users");

// Get with headers
map<string> headers = {"Accept": "application/json"};
json users = check httpClient->get("/api/users", headers = headers);
post

Sends an HTTP POST request with a payload.

Parameters:

NameTypeRequiredDescription
pathstringYesRequest path.
messageRequestMessageYesRequest payload (JSON, XML, text, binary, or Request).
headersmap<string|string[]>NoOptional HTTP headers.
mediaTypestringNoContent type of the payload.
targetTypeTargetTypeNoExpected return type for automatic data binding. Inferred from the call site when omitted.

Returns: targetType|ClientError

Sample code:

json payload = {name: "John", email: "[email protected]"};
json response = check httpClient->post("/api/users", payload);
put

Sends an HTTP PUT request with a payload.

Parameters:

NameTypeRequiredDescription
pathstringYesRequest path.
messageRequestMessageYesRequest payload.
headersmap<string|string[]>NoOptional HTTP headers.
mediaTypestringNoContent type of the payload.
targetTypeTargetTypeNoExpected return type for automatic data binding. Inferred from the call site when omitted.

Returns: targetType|ClientError

Sample code:

json payload = {name: "John Updated", email: "[email protected]"};
json response = check httpClient->put("/api/users/123", payload);
patch

Sends an HTTP PATCH request with a partial payload.

Parameters:

NameTypeRequiredDescription
pathstringYesRequest path.
messageRequestMessageYesRequest payload.
headersmap<string|string[]>NoOptional HTTP headers.
mediaTypestringNoContent type of the payload.
targetTypeTargetTypeNoExpected return type for automatic data binding. Inferred from the call site when omitted.

Returns: targetType|ClientError

Sample code:

json payload = {email: "[email protected]"};
json response = check httpClient->patch("/api/users/123", payload);
delete

Sends an HTTP DELETE request.

Parameters:

NameTypeRequiredDescription
pathstringYesRequest path.
messageRequestMessageNoOptional request payload. Defaults to ().
headersmap<string|string[]>?NoOptional HTTP headers. Defaults to ().
mediaTypestring?NoContent type of the payload. Defaults to ().
targetTypeTargetTypeNoExpected return type for automatic data binding. Inferred from the call site when omitted.

Returns: targetType|ClientError

Sample code:

http:Response response = check httpClient->delete("/api/users/123");
head

Sends an HTTP HEAD request. Returns only response headers without a body.

Parameters:

NameTypeRequiredDescription
pathstringYesRequest path.
headersmap<string|string[]>NoOptional HTTP headers.

Returns: Response|ClientError

Sample code:

http:Response response = check httpClient->head("/api/users");
string? contentType = response.getHeader("Content-Type");
options

Sends an HTTP OPTIONS request to discover supported methods.

Parameters:

NameTypeRequiredDescription
pathstringYesRequest path.
headersmap<string|string[]>NoOptional HTTP headers.
targetTypeTargetTypeNoExpected return type for automatic data binding. Inferred from the call site when omitted.

Returns: targetType|ClientError

Sample code:

http:Response response = check httpClient->options("/api/users");
string? allowedMethods = response.getHeader("Allow");
execute

Sends an HTTP request with a dynamically specified method.

Parameters:

NameTypeRequiredDescription
httpVerbstringYesHTTP verb (e.g., "GET", "POST"). Case-sensitive — use the http:Method type for the standard verbs.
pathstringYesRequest path.
messageRequestMessageYesRequest payload.
headersmap<string|string[]>?NoOptional HTTP headers. Defaults to ().
mediaTypestring?NoContent type of the payload. Defaults to ().
targetTypeTargetTypeNoExpected return type for automatic data binding. Inferred from the call site when omitted.

Returns: targetType|ClientError

Sample code:

http:Response response = check httpClient->execute("GET", "/api/users", ());
forward

Forwards an incoming HTTP request to another endpoint, preserving the original request headers and payload.

Parameters:

NameTypeRequiredDescription
pathstringYesTarget path.
requestRequestYesThe original HTTP request to forward.
targetTypeTargetTypeNoExpected return type for automatic data binding. Inferred from the call site when omitted.

Returns: targetType|ClientError

Sample code:

// Inside a service resource
resource function get proxy(http:Request req) returns http:Response|error {
return check httpClient->forward("/backend/api", req);
}

Asynchronous requests

submit

Submits an asynchronous HTTP request and returns an HttpFuture for later retrieval.

Parameters:

NameTypeRequiredDescription
httpVerbstringYesHTTP verb. Case-sensitive — use the http:Method type for the standard verbs.
pathstringYesRequest path.
messageRequestMessageYesRequest payload.

Returns: HttpFuture|ClientError

Sample code:

http:HttpFuture future = check httpClient->submit("GET", "/api/long-running-task", ());
// ... do other work ...
http:Response response = check httpClient->getResponse(future);
getResponse

Retrieves the response for a previously submitted asynchronous request.

Parameters:

NameTypeRequiredDescription
httpFutureHttpFutureYesThe future returned by submit.

Returns: Response|ClientError

Sample code:

http:HttpFuture future = check httpClient->submit("GET", "/api/data", ());
http:Response response = check httpClient->getResponse(future);

HTTP/2 server push

hasPromise

Checks whether the server has sent a push promise for additional resources on this future.

Parameters:

NameTypeRequiredDescription
httpFutureHttpFutureYesThe future from a previous asynchronous invocation.

Returns: boolean

Sample code:

http:HttpFuture future = check httpClient->submit("GET", "/index.html", ());
boolean hasMore = httpClient->hasPromise(future);
getNextPromise

Returns the next server push promise associated with the future.

Parameters:

NameTypeRequiredDescription
httpFutureHttpFutureYesThe future from a previous asynchronous invocation.

Returns: PushPromise|ClientError

Sample code:

http:PushPromise promise = check httpClient->getNextPromise(future);
getPromisedResponse

Retrieves the response data that was proactively pushed by the server for a given promise.

Parameters:

NameTypeRequiredDescription
promisePushPromiseYesThe push promise returned by getNextPromise.

Returns: Response|ClientError

Sample code:

http:Response pushed = check httpClient->getPromisedResponse(promise);
rejectPromise

Rejects a server push promise, declining to receive the additional resource.

Parameters:

NameTypeRequiredDescription
promisePushPromiseYesThe push promise to reject.

Sample code:

httpClient->rejectPromise(promise);

Resource methods

The HTTP client also supports resource method syntax for a cleaner API style. Path segments are provided as part of the method call:

// GET /api/users/123
json user = check httpClient->/api/users/["123"];

// POST /api/users with JSON payload
json newUser = check httpClient->/api/users.post({name: "John", email: "[email protected]"});

// DELETE /api/users/123
http:Response res = check httpClient->/api/users/["123"].delete();

Utility methods

getCookieStore

Returns the cookie store associated with this client, or () if cookie handling is disabled.

Returns: CookieStore?

Sample code:

http:CookieStore? store = httpClient.getCookieStore();
circuitBreakerForceClose

Forces the circuit breaker to the closed state.

Sample code:

httpClient.circuitBreakerForceClose();
circuitBreakerForceOpen

Forces the circuit breaker to the open state.

Sample code:

httpClient.circuitBreakerForceOpen();
getCircuitBreakerCurrentState

Returns the current state of the circuit breaker. Panics with an http:ClientError if invoked on a client that was not configured with a circuit breaker.

Returns: CircuitState

Sample code:

http:CircuitState state = httpClient.getCircuitBreakerCurrentState();

StatusCodeClient

Identical to Client but provides status-code-based response binding. Returns typed responses for different HTTP status codes, enabling compile-time checks for response handling.

Configuration

Same as Client configuration.

Initializing the client

import ballerina/http;

http:StatusCodeClient scClient = check new ("https://api.example.com");

Operations

The StatusCodeClient has the same remote methods as Client (get, post, put, patch, delete, head, options, execute, forward, submit, getResponse).

The key difference is that response types are bound to HTTP status codes:

type UserResponse record {|
*http:Ok;
record {|string name; string email;|} body;
|};

type UserNotFound record {|
*http:NotFound;
record {|string message;|} body;
|};

UserResponse|UserNotFound|error response = scClient->get("/api/users/123");

if response is UserResponse {
// Handle 200 OK
} else if response is UserNotFound {
// Handle 404 Not Found
}

FailoverClient

Attempts subsequent endpoints on failure. If a request to the first endpoint fails, it automatically tries the next endpoint in the list.

Configuration

In addition to the failover-specific fields below, FailoverClientConfiguration includes all fields from Client configuration (httpVersion, timeout, auth, retryConfig, secureSocket, circuitBreaker, poolConfig, cache, compression, followRedirects, cookieConfig, responseLimits, proxy, validation, laxDataBinding, etc.).

FieldTypeDefaultDescription
targetsTargetService[][]Array of target endpoints.
failoverCodesint[][501, 502, 503, 504]HTTP status codes that trigger failover.
intervaldecimal0Failover delay interval in seconds.

Initializing the client

import ballerina/http;

http:FailoverClient foClient = check new ({
targets: [
{url: "https://primary.example.com"},
{url: "https://secondary.example.com"},
{url: "https://tertiary.example.com"}
],
failoverCodes: [500, 502, 503]
});

Operations

Same remote methods as Client. Additionally:

getSucceededEndpointIndex

Returns the index of the endpoint that successfully processed the last request.

Returns: int

Sample code:

http:Response response = check foClient->get("/api/data");
int succeededIdx = foClient.getSucceededEndpointIndex();

LoadBalanceClient

Distributes requests across multiple endpoints using round-robin load balancing.

Configuration

In addition to the load-balance-specific fields below, LoadBalanceClientConfiguration includes all fields from Client configuration.

FieldTypeDefaultDescription
targetsTargetService[][]Array of target endpoints.
lbRuleLoadBalancerRule?()Load balancing strategy. When (), the client falls back to built-in round-robin.
failoverbooleantrueEnable failover when an endpoint fails.

Initializing the client

import ballerina/http;

http:LoadBalanceClient lbClient = check new ({
targets: [
{url: "https://server1.example.com"},
{url: "https://server2.example.com"},
{url: "https://server3.example.com"}
]
});

Operations

Same remote methods as Client (get, post, put, patch, delete, head, options, execute, forward, submit, getResponse).

// Requests are distributed across the three targets
json response = check lbClient->get("/api/data");