Run a Python script on a static website

Introduction

In this tutorial, you’ll learn how to create and call a Flex.io API endpoint that executes a serverless function written in a Python script.

Specifically, you’ll learn how to:

  • Create the function definition
  • Set up the API endpoint to execute the function
  • Call the function from a static website

This technique is useful if you want to:

  • Keep the simplicity of developing and deploying a static website
  • Add some functionality to the static website that would normally require a server
  • Offload processing to a backend, reducing network overhead and client load
  • Leverage langauges or libraries normally unavailable on the client side, such as Python Pandas

Setup

To complete this tutorial, you’ll need:

Create the function definition

  1. Create a new pipe in Flex.io

  2. By default, you’ll see a sample Execute Task, which defines your function. In the drop-down menu, you’ll see options for Python or Node.js, so if you prefer to run Node.js from a static webpage, you can do that as well. However, for this tutorial, make sure ‘Python’ is selected, then paste the following script in the Execute Task:

  1. After saving your changes, press the “TEST” button in the upper right of the Pipe Builder. You should see “Hello, World.” appear in the pipe output.

Set up the API endpoint to execute the function

Next, you’ll need to set up the API endpoint to run the function you just created.

  1. First, turn on your pipe to activate it.

  2. Then, scroll down to the Deployment section and check the box next to Run using an API endpoint to see your API endpoint and API key.

  3. Next to the endpoint, which by default uses the unique pipe EID as a reference, click the Edit button to add an alias to your pipe as follows: example-run-python-script-on-a-static-website.

  4. To quickly test the endpoint, copy the HTTPS endpoint and paste it into your browser to see your data; the HTTPS endpoint will look like this (where {token} is your unique API key):

https://api.flex.io/v1/me/pipes/example-run-python-script-on-a-static-website/run?flexio_api_key={token}

Call the function from a static website

Of course, now that you have your endpoint, you’re now ready to invoke your Python script in any server or client code that allows you to make an HTTP request. For example, here’s how you’d call it from a static website using Axios

HTML Script:

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script>
axios({
method: 'post',
url: 'https://api.flex.io/v1/me/pipes/example-run-python-script-on-a-static-website/run',
headers: {
Authorization: 'Bearer {token}'
}
})
.then(response => {
console.log(response.data)
})
.catch(response => {
})
</script>