Skip to main content

Triggers

The ballerina/http module supports inbound HTTP request handling through its listener and service model. When HTTP requests arrive, the http:Listener dispatches them to matching service resource methods automatically: your service reacts to each request by HTTP method and path.

Three components work together:

ComponentRole
http:ListenerBinds to a network port and accepts incoming HTTP connections.
http:ServiceDefines resource methods that handle requests by HTTP method and URL path.
http:CallerRepresents the client connection, used to send responses back.

For outbound HTTP operations, see the Action Reference.


Listener

The http:Listener binds to a port and dispatches incoming HTTP requests to attached services.

Configuration

FieldTypeDefaultDescription
hoststring"0.0.0.0"Network interface to bind to.
httpVersionHttpVersionHTTP_2_0HTTP protocol version (HTTP_1_0, HTTP_1_1, HTTP_2_0).
http1SettingsListenerHttp1Settings{}HTTP/1.x specific settings.
secureSocketListenerSecureSocket()TLS/SSL configuration (certificate, key, protocol).
timeoutdecimal60Period of time in seconds that a connection waits for a read/write operation. Use 0 to disable timeout.
serverstring()Server header value.
requestLimitsRequestLimitConfigs{}Request size limits (max URI length, header size, body size).
http2InitialWindowSizeint65535HTTP/2 flow control window size.
minIdleTimeInStaleStatedecimal300HTTP/2 only. Time in seconds a connection that has received a GOAWAY is kept open. Set to -1 to close the connection only after all in-flight streams complete.
timeBetweenStaleEvictiondecimal30HTTP/2 only. Interval in seconds between runs that evict GOAWAY-marked stale connections.

Initializing the listener

Basic listener on a port:

import ballerina/http;

listener http:Listener httpListener = new (9090);

With host binding and request limits:

import ballerina/http;

listener http:Listener httpListener = new (9090, {
host: "0.0.0.0",
requestLimits: {
maxUriLength: 4096,
maxHeaderSize: 8192,
maxEntityBodySize: 10485760
}
});

With TLS/SSL:

import ballerina/http;

listener http:Listener secureListener = new (9443, {
secureSocket: {
key: {
certFile: "/path/to/cert.pem",
keyFile: "/path/to/key.pem"
}
}
});

Attaching a service to multiple listeners:

import ballerina/http;

listener http:Listener httpListener = new (9090);
listener http:Listener httpsListener = new (9443, {
secureSocket: {key: {certFile: "server.crt", keyFile: "server.key"}}
});

service /api on httpListener, httpsListener {
// service handles both HTTP and HTTPS traffic
}

Service

An http:Service is a Ballerina service attached to an http:Listener. It defines resource methods that handle incoming HTTP requests based on the HTTP method and URL path.

Resource method signatures

HTTP MethodResource AccessorSignature
GETgetresource function get path() returns ResponseType
POSTpostresource function post path(@http:Payload PayloadType payload) returns ResponseType
PUTputresource function put path(@http:Payload PayloadType payload) returns ResponseType
PATCHpatchresource function patch path(@http:Payload PayloadType payload) returns ResponseType
DELETEdeleteresource function delete path() returns ResponseType
HEADheadresource function head path() returns ResponseType
OPTIONSoptionsresource function options path() returns ResponseType
Anydefaultresource function default path() returns ResponseType
note

You only need to implement the HTTP methods your service supports. Unhandled methods automatically return 405 Method Not Allowed.

Parameter binding

Resource methods can accept the following parameter types:

AnnotationTypeDescription
(path segment)string, int, float, decimal, boolean (and their array forms)Path parameters extracted from the URL. Use [string... path] to capture remaining segments as a rest parameter.
@http:Payloadjson, xml, string, byte[], map<json>, table<map<json>>, record, plus arrays and readonly variants of the aboveRequest body payload. If the parameter type is a structural type, the annotation is optional.
@http:Headerstring, int, float, decimal, boolean, their array forms, and the nilable variants of all of these. Also a record type whose fields follow the same rules.Specific request header values.
@http:Querystring, int, float, decimal, boolean, their array forms, and the nilable variants of all of these.Query parameter values.
N/Ahttp:CallerClient connection for sending responses manually.
N/Ahttp:RequestFull request object for advanced access.
N/Ahttp:HeadersRequest header accessor.
N/Ahttp:RequestContextPer-request context used to pass values between interceptors and resources.

Return types

Resource methods can return any of the following types to send a response:

Return TypeDescription
string, json, xml, byte[]Payload sent with the default status code (201 CREATED for POST resources and 200 OK for others) and appropriate content type.
recordSerialized as JSON with the default status code (201 CREATED for POST resources and 200 OK for others).
http:Ok, http:Created, http:Accepted, ...Status-code-specific response records with optional body and headers.
http:ResponseFull control over status code, headers, and body.
errorReturns 500 Internal Server Error.
http:StatusCodeResponseUnion of all status code response records.

Full usage example

import ballerina/http;

type User record {|
string name;
string email;
|};

listener http:Listener httpListener = new (9090);

service /api on httpListener {

// GET /api/greeting?name=John
resource function get greeting(string name = "World") returns string {
return "Hello, " + name + "!";
}

// GET /api/users/123
resource function get users/[int id]() returns User|http:NotFound {
// Look up user by ID
if id == 123 {
return {name: "John", email: "[email protected]"};
}
return http:NOT_FOUND;
}

// POST /api/users
resource function post users(User user) returns http:Created|error {
// Create the user
return {body: {message: "User created", name: user.name}};
}

// DELETE /api/users/123
resource function delete users/[int id]() returns http:NoContent {
// Delete the user
return http:NO_CONTENT;
}
}

Interceptors

Interceptors process requests and responses before and after resource execution, enabling cross-cutting concerns like logging, authentication, and header manipulation.

TypeDescription
RequestInterceptorProcesses incoming requests before the resource method is invoked.
ResponseInterceptorProcesses outgoing responses after the resource method completes.
RequestErrorInterceptorHandles errors during request processing.
ResponseErrorInterceptorHandles errors during response processing.

Define an interceptor as a service class that includes one of the four interceptor types:

import ballerina/http;
import ballerina/log;

service class LoggingInterceptor {
*http:RequestInterceptor;

resource function 'default [string... path](http:RequestContext ctx, http:Request req)
returns http:NextService|error? {
log:printInfo("Request received", method = req.method, path = req.rawPath);
return ctx.next();
}
}

Engage the interceptor by declaring the target service as http:InterceptableService and returning interceptor instances from createInterceptors():

service http:InterceptableService /api on httpListener {

public function createInterceptors() returns LoggingInterceptor {
return new LoggingInterceptor();
}

resource function get greeting() returns string {
return "Hello!";
}
}

createInterceptors() may return a single interceptor or an array; the elements run in order on the request side and in reverse order on the response side.


Supporting types

RequestLimitConfigs

FieldTypeDefaultDescription
maxUriLengthint4096Maximum URI length in bytes.
maxHeaderSizeint8192Maximum total header size in bytes.
maxEntityBodySizeint-1Maximum request body size in bytes (-1 for unlimited).

ListenerSecureSocket

FieldTypeDescription
keyCertKeyServer certificate and private key.
mutualSslrecordMutual SSL configuration (client certificate validation).
protocolrecordTLS protocol version constraints.
certValidationrecordCertificate validation type (OCSP, CRL).
handshakeTimeoutdecimalTLS handshake timeout in seconds.
sessionTimeoutdecimalTLS session timeout in seconds.

CorsConfig

FieldTypeDescription
allowOriginsstring[]Permitted origin domains.
allowMethodsstring[]Permitted HTTP methods.
allowHeadersstring[]Permitted request headers.
exposeHeadersstring[]Headers exposed to the client.
allowCredentialsbooleanWhether to allow credentials.
maxAgeintPre-flight response cache duration in seconds.