Sending a Post Request from Ballerina

359 views Asked by At

I want to send a post request using ballerina to get a access token from the Choreo Dev Portal. I am able to do it using postman. But unable to make it work in Ballerina code level. it gives 415 - unsupported media type error. Need some Help in Ballerina

import ballerina/http;
import ballerina/io;
import ballerina/url;

public function main() returns error? {

    final http:Client clientEndpoint = check new ("https://sts.choreo.dev");
    http:Request request = new();

    string payload = string`grant_type=urn:ietf:params:oauth:grant-type:token-exchange&
    subject_token=*******&
    subject_token_type=urn:ietf:params:oauth:token-type:jwt&
    requested_token_type=urn:ietf:params:oauth:token-type:jwt`;

    string encodedPayload = check url:encode(payload, "UTF-8");
    io:print(encodedPayload);
    
    request.setTextPayload(encodedPayload);
    request.addHeader("Authorization","Basic *****");
    request.addHeader("Content-Type","application/x-www-form-urlencoded");
    io:print(request.getTextPayload());

    json resp = check clientEndpoint->post("/oauth2/token",request);
    io:println(resp.toJsonString());
}

I was expecting an access token from Choreo Devportal for the particular application.

2

There are 2 answers

0
Chamil E On

Change the Content-type header setting method from addHeader() to setHeader().

The request.setTextPayload(encodedPayload); will set the Content-type as text/plain as the default content type header.

Later request.addHeader("Content-Type","application/x-www-form-urlencoded"); is executed. The addHeader() method will append the new value to the same header in addition to the previously added text/plain. But the setHeader() will replace the previously set header which is the correct way in this scenario.

However better way is to pass the Content-type as the second param of setXXXPayload() method.

request.setTextPayload(encodedPayload, "application/x-www-form-urlencoded");

0
Thenusan Santhirakumar On
import ballerina/http;
import ballerina/io;
import ballerina/mime;

public function main() returns error? {

    // Creates a new client with the backend URL.
    final http:Client clientEndpoint = check new ("https://sts.choreo.dev");
    json response = check clientEndpoint->post("/oauth2/token", 
        {
            "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
            "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
            "requested_token_type":"urn:ietf:params:oauth:token-type:jwt",
            "subject_token":"****"
        },
        {
            "Authorization": "Basic ****"
        }, 
        mime:APPLICATION_FORM_URLENCODED
       
    );
    io:println(response.toString());
}

This is the recommended way to send the post request with the form URL encoded payload.