Uploading a REST API response to an SFTP server in Ballerina

42 Views Asked by At

What is the best way to gather a response from a REST API endpoint and upload to SFTP. Is there a native type support to stream directly from a response to <stream>byte[], which is needed for an SFTP client?

1

There are 1 best solutions below

0
Shammi Kolonne On

There's a couple of ways to achieve this,

  1. You can get the response from the REST API as a json object and try the following to get a byte stream.
json response = {"name":"John", "age":30};
stream<byte> byteResponse = response.toString().toBytes().toStream();
  1. You can use the getByteStream() method of the ballerina/http module to get the request payload as a stream of byte[].
http:Client catClient = check new ("https://cat-fact.herokuapp.com");

public function main() returns error? {
    http:Response res = check catClient->/facts;
    stream<byte[], io:Error?> byteRes= check res.getByteStream();
}
  1. You can use the targetType parameter of http resource call function
type ResponseType byte[];

public function main() returns error? {
    http:Client cl = check new("http://localhost:9090");
    byte[] response = check cl->/path(targetType = ResponseType);
    stream<byte> s = response.toStream();
}

Apart from the above, if there is no strict requirement to upload to the SFTP server as stream<byte[]>, you can get a json response from the http client and store it directly.

http:Client httpClient = check new("https://api.chucknorris.io/");
json joke = check httpClient->get("jokes/random");
ftp:Client ftpClient = check new(clientConfig = {...});
ftp:Error? e = ftpClient->put("file.txt", joke);