how to return HTTP status code in Open FaaS?

1.1k views Asked by At

How can a function deployed in openfaas return different HTTP status code to the caller? Like 4xx codes.

As per documentation, the watchdog would process the stdout or stderr for either a http status 200 or 5xx.

Is there a way to change the status like 400, 409 etc? I am using csharp template as downloaded by faas-cli

3

There are 3 answers

1
sutoL On BEST ANSWER

You cant, as stated here https://github.com/openfaas/faas-netes/issues/147

The solution suggested is to return a payload with the status code, and parse the payload on the receiving end.

0
negstek On

After a lot of research about how to do it in python, dont use the casual template, you should use the python-flask template. It works like a charm.

4
Kyle On

The default python template appears to return 200, even when you system.exit(1) or throw an exception. I assume other older templates behave similarly, and that this is expected of the classic watchdog.

However, if the language template you use supports running the new of-watchdog, I think it can return non-200 codes, like 400, 404, etc. You can download these templates using the faas-cli, they're from the openfaas-incubator project and the community.

I just confirmed using the python3-http language/template from openfaas-incubator, and csharp-httprequest from distantcam that non-200 codes can be returned like 400, 404, etc.

This will list available templates:

faas-cli template store list

To install the csharp template I tested with:

faas-cli template store pull distantcam/csharp-httprequest

The OOTB handler for csharp-httprequest can be easily modified like this to return a 400:

using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;

namespace Function
{
    public class FunctionHandler
    {
        public async Task<(int, string)> Handle(HttpRequest request)
        {
            var reader = new StreamReader(request.Body);
            var input = await reader.ReadToEndAsync();

            return (400, $"Hello! Your input was {input}");
        }
    }
}