This page will walk you through a couple of examples of working with HTTP in Binaris functions.

If you are new to Binaris is it recommended that you look through the previous getting-started tutorials:

Note: the instructions below assume you are using MacOS, Ubuntu or Debian.

Working with HTTP

Serverless functions are commonly used as HTTP endpoints. They are used as APIs to perform many tasks and can even be used to serve Web pages. To comply with HTTP conventions, it is necessary to manipulate attributes such as HTTP return code and HTTP headers. Binaris functions provide an easy and intuitive way to quickly achieve common HTTP-related tasks.

How it works

Binaris functions support a context parameter in the function signature. The context object provides developers with access to the HTTP request and response payloads. context.Request includes the content of the HTTP call including the body, headers and query strings. context.HTTPResponse provides developers with access to the content and headers of the returning payload.

Public functions

Binaris functions are secured by default, they are protected by an API Key that has to be passed as an HTTP header. However, there are many cases where functions should be exposed as public http end-points. Adding the keyword public_ before a function name allows it to be called without the need for an API Key.

Below are a few common HTTP scenarios:

1. Create an HTML response

In some cases you may want your Serverless function returning HTML content so it can be visible in a browser. This allows you to save on the cost of setting up and hosting a Web server.

Create the function

$ mkdir HelloHTML
$ cd HelloHTML
$ bn create node8 public_HelloHTML

Create the HTTP response

Replace the content of the function.js with the code below:

exports.handler = (body, context) => {

  const name = context.request.query.name || body.name || 'World';

  return new context.HTTPResponse({
    statusCode: 200,
    headers: {
      'Content-Type': 'text/html',
    },  
    body: `<html><body>Hello ${name}</body></html>`
  });
};

Deploy and Invoke the function

$ bn deploy public_HelloHTML
Deployed function public_HelloHTML
Invoke with one of:
  "bn invoke public_HelloHTML"
  "https://run-sandbox.binaris.com/v2/run/<Your_Account_Number>/public_HelloHTML"

$ bn invoke public_HelloHTML --data '{ "name":"World" }'
<html><body>Hello World</body></html>

You can also browse to https://run-sandbox.binaris.com/v2/run//public_HelloHTML and you will see "Hello World" in the browser window.

What happened

The function returns a new context.HTTPResponse object. It sets the response code to 200 (OK) and defines the content type to text/html. The HTML body is then set to include minimal HTML code containing the incoming name argument passed during the function invocation.

2. Implement CORS

Cross-Origin Resource Sharing (CORS) allows clients to leverage Web-based APIs that are hosted on different domains. Browsers block client side code from accessing URLs on different domains for security reasons. To provide access, the URL being called needs to return an Access-Control-Allow-Origin header with the URL of the site that is allowed to access the resource as a value for the header.

Create the function

$ mkdir HelloCORS
$ cd HelloCORS
$ bn create node8 HelloCORS

Set the CORS header

Replace the content of the function.js with the code below:

exports.handler = (body, context) => {
  const output = "output";
  return new context.HTTPResponse({
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': 'example.com',
    },
    body: output,
  });
};

Deploy and Invoke the function

$ bn deploy HelloCORS
Deployed function HelloCORS
Invoke with one of:
  "bn invoke HelloCORS"
  "curl -H X-Binaris-Api-Key:<Your_API_Key> https://run-sandbox.binaris.com/v2/run/<Your_Account_Number>/HelloCORS"

curl -I -H X-Binaris-Api-Key:<Your_API_Key> https://run-sandbox.binaris.com/v2/run/<Your_Account_Number>/HelloCORS
HTTP/1.1 200 OK
Server: openresty/1.13.6.1
Date: Sat, 08 Dec 2018 03:18:46 GMT
Connection: keep-alive
X-Binaris-Bolt-Duration-Usecs: 2229.459
**Access-Control-Allow-Origin: example.com**
X-Binaris-Request-ID: a6164b6deabae2ea5bb4c110411216a9

As you can see above, the function return an Access-Control-Allow-Origin header.

3. Redirecting a response

In some cases it is very useful to have an HTTP endpoint redirect the caller to a different location. A great example for this would be creating a URL shortening service that compresses a long Web address to a shorter string that can be easily memorized.

Create the function

$ mkdir HelloRedirect
$ cd HelloRedirect
$ bn create node8 public_HelloRedirect

Implement the redirect

Replace the content of the function.js with the code below:

exports.handler = async (body, context) => {
  const target = context.request.query.target || body.target || 'http://www.binaris.com';
  return new context.HTTPResponse(
    {
      statusCode: 302,
      headers: {
        'Location': `${target}`,
      }
    }
  )
};

Deploy and Invoke the function

$ bn deploy public_HelloRedirect
Deployed function public_HelloRedirect
Invoke with one of:
  "bn invoke public_HelloRedirect"
  "https://run-sandbox.binaris.com/v2/run/<Your_Account_Number>/public_HelloRedirect"

Invoke the function by navigating to the below URL where the target query string parameter is used to determine the HTTP redirection.

https://run-sandbox.binaris.com/v2/run/<Your_Account_Number>/public_HelloRedirect?target=http://www.google.com

Conclusion

Binaris functions are a great platform for building Web based APIs. We can’t wait to see what you build!

Tip

You can use bn --help to see all the available CLI commands.

What’s next

To learn more about Binaris functions, review the below documents: