Back to Examples

HTTP service - Request/Response object

http:Request and http:Response objects are Ballerina abstractions for HTTP request and HTTP response respectively. They are considered low-level abstractions which are used to implement high-level abstractions such as data-binding, header mapping, query parameter mapping, etc. They can be used both on the client side and the service side. They are useful when implementing advanced scenarios such as gateways, proxy services, handling multipart requests, etc. In most cases, the http:Request and the http:Response objects are not needed as higher-level abstractions can do the same thing.

import ballerina/http;

type Album readonly & record {|
    string title;
    string artist;
|};

table<Album> key(title) albums = table [
    {title: "Blue Train", artist: "John Coltrane"},
    {title: "Jeru", artist: "Gerry Mulligan"}
];

service / on new http:Listener(9090) {

    // The request is defined in the signature parameter.
    resource function post albums(http:Request request) returns http:Response|error {
        json payload = check request.getJsonPayload();
        Album album = check payload.cloneWithType();
        albums.add(album);

        // Create a response and populate the headers/payload.
        http:Response response = new;
        response.setPayload(album);
        response.setHeader("x-music-genre", "Jazz");
        return response;
    }
}

Run the service as follows.

$ bal run http_request_response.bal

Invoke the service by executing the following cURL command in a new terminal.

$ curl http://localhost:9090/albums -H "Content-type:application/json" -d "{\"title\": \"Sarah Vaughan and Clifford Brown\", \"artist\": \"Sarah Vaughan\"}"{"title":"Sarah Vaughan and Clifford Brown", "artist":"Sarah Vaughan"}

Tip: You can invoke the above service via the Send request/Receive response client example.

Related links

PreviousDefault resource
NextCaller object