Note: πŸ“˜ This documentation is a work in progress and is subject to frequent changes.

Documentation πŸ“„

Welcome to the documentation page. Here you'll find all the relevant information about setting up, integrating, and using the API Gateway and its related components.

Tutorial: Hello World! 🌍

This is a simple tutorial to get you started with the API Gateway. In this tutorial, we will create a simple "Hello World!" API using the API Gateway.

Step 1: Create a function πŸ› οΈ

To create a function, go to the Functions page and click on the "Save Function" button. Enter a name for your function and enter this code:

This function will return a simple "Hello World!" message when called. Save the function, click on Edit and then Deploy to deploy the function.

Step 2: Create a route 🚦

All users have a default gateway with the prefix "/". Go to Gateways and click on the "New Route" button. Enter the path "hello" for the route and select the method "GET". Select the function you just created from the dropdown list. Click on the "Save Route" button to create the route.

Now you can test your API by going to the URL "https://your-username.thread4.eu/hello". You should see the "Hello World!" message returned by your function. 🌐

Section 1: Gateway Overview

A Gateway acts as the entry point for your routes, defined by a prefix that all associated routes automatically inherit. Each user has one Gateway, created by default with the prefix "/". While a Gateway can have many routes, its prefix must be unique and cannot conflict with existing route paths. Valid prefixes may only include letters, numbers, and slashes ("/"). Every Gateway also requires a unique name for easy identification. 🏷️

πŸ›£οΈ Section 2: Route Overview

A Route defines a single endpoint within a Gateway. Each Route belongs to a specific Gateway and User, and can optionally be linked to a Function that executes when the route is triggered. Routes are cached for 60 seconds, meaning that if a route is not accessed within that time frame, it will be removed from the cache and changes will not be reflected until the cache is refreshed. ⏳

Every Route must specify an HTTP method, such as GET or POST, and a path that uniquely identifies the endpoint within its Gateway. The path must be made up of only letters and numbersβ€”it cannot include slashes or special characters, and it must not start with a "/". To ensure clarity and manageability, path names are limited to 64 characters. ✏️

Special routes with parameters in path πŸ”§

Routes can also include parameters in the path, allowing for dynamic routing based on user input.For example, a route with the path "user/<id>" would match requests to "/user/123" and "/user/456", where "123" and "456" are the values of the "id" parameter. The parameter value can be accessed in the function using the event object, which contains the request data. πŸ“¦

API Tokens πŸ”‘

πŸ›‘οΈ API Tokens can be generated for individual routes from their edit pages. These tokens restrict access to the route, allowing only authorized requests.

πŸ”’ Tokens must be included in the Authorization header as a Bearer token when making requests.

🌐 To make a route public again, simply delete all associated tokens.

Example πŸ“–

Suppose you have a gateway with the prefix "/api" and you want to create a route for adding a new user.You could define a route with the path "add-user" and the method POST.This would create an endpoint at "/api/add-user" that accepts POST requests. πŸ“¨If you also wanted to create a route for retrieving user information, you could define another route with the path "get-user" and the method GET.This would create an endpoint at "/api/get-user" that accepts GET requests. πŸ“€

Section 3: Functions 🧩

Functions are dynamic Python functions that can be linked to a route. They run on a custom Python engine powered by FastAPI. πŸš€ This enables real-time updates without needing server restarts.

Functions are cached for 60 seconds. If a function is not accessed within this time, it will be removed from the cache. Changes will not take effect until the cache is refreshed. ⏳

Functions must define a "handler" function that accepts two arguments: "event" and "context." This interface is similar to AWS Lambda.

The "event" parameter contains the request data. The "context" parameter provides metadata about the request.

The function can return either:

  • A string or a dictionary as the body.
  • A response dictionary with "headers," "status_code," and "body." πŸ› οΈ

Websocket Support πŸ”Œ

Functions can also support WebSocket connections. To enable this:

  • Set the route method to "WEBSOCKET".
  • Update the function handler to accept three arguments:
    • data: The message received from the client.
    • respond: A function to send a message back to the client.
    • broadcast: A function to send a message to all connected clients of that route.

Allowed response headers πŸ“œ

  • Content-Type
  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers
  • X-Custom-Header

Allowed Modules and Integrations πŸ”—

The following modules are allowed in your functions:
  • json
  • datetime
  • math
  • More modules will be added in the future. πŸ“¦

Examples πŸ“

Example of a Python function that returns HTML πŸ–₯️

Example of a function which returns HTML, with content type and status code πŸ–‹οΈ

Example of a function which returns JSON πŸ“Š:

Example of a function which returns JSON, with content type and status code πŸ›‘οΈ

Example function using Thread4 module to retrieve HTML file πŸ“‚.

Example function using Thread4 Template module (Jinja2) to render HTML file πŸ–ΌοΈ.

Why is my function not working? ❓

If your function is not working, it may be due to one of the following reasons:
  • The function is not deployed. Make sure to deploy your function after making changes. πŸš€
  • The function is not associated with a route. Make sure to associate your function with a route. πŸ”—
  • The function is not returning a valid response. Make sure to return a valid response from your function. βœ…
  • The function is not using the correct event and context parameters. Make sure to use the correct parameters in your function. πŸ› οΈ

Thread4 Module 🧡

The Thread4 module is a custom module that provides additional functionality for your functions.It includes models to retrieve documents and render HTML templates (Jinja2). πŸ“„

Thread4 Document Model πŸ“œ

The Thread4 Document model allows you to retrieve documents from your API. The model provides methods to retrieve documents by their name. πŸ—‚οΈ

Important Notice ⚠️

The Document and Logger model requires the handler to be async.

Example of retrieving a document using the Thread4 Document Model:

from Thread4 import Documents
docs = Documents()
await docs.get("index.html")

Thread4 Template Model πŸ–ΌοΈ

The Thread4 Template model allows you to render HTML templates using Jinja2. The model provides methods to render templates with context data. πŸ–‹οΈ

Example of rendering a template using the Thread4 Template Model:

from Thread4 import Template
template = Template("<h1>{{ title }} - {{ name }}</h1>")
await template.render(tile="Hello World", name="Thread4")

Or you can use the Template class to render a template from a string:

from Thread4 import Template
template = Template()
await template.render(template_str="<h1>{{ title }} - {{ name }}</h1>", tile="Hello World", name="Thread4")

Thread4 Logger Model πŸ“

The Thread4 Logger model allows you to log custom messages to the API logs. This model requires the handler to be async.

Example of logging a message using the Thread4 Logger Model:

from Thread4 import Logger
logger = Logger()
await logger.info("Hello World")
await logger.warning("Hello World")
await logger.error("Hello World")

Important: All logs need to be awaited

Section 4: Documents πŸ“„

Documents are rich text files or HTML files that can be served from your API. They can be fetched through a custom Python Module that can be imported into your functions. Allowing users to create HTML web pages and serve them from their API. 🌐Documents are not cached and are served directly from the API.

Documents can be used to store and manage content, such as user guides, API documentation, or any other type of information that needs to be served over the web. πŸ“š

Section 5: Integrations πŸ”—

Integrations are a planned feature that will allow users to connect their applications with external services and APIs. 🌐

This will enable users to easily integrate their applications with third-party services, such as databases, authentication providers, and other APIs. 🀝

  • PostgresSQL / SQLite3
  • Redis
  • Slack
  • More to come! πŸš€

This will help users to easily connect their applications with external services and APIs, making it easier to build and deploy complex applications. πŸ› οΈ

Storage (Planned) πŸ—„οΈ

Storage is a planned feature that will allow users to manage JSON blobs and key-value stores. πŸ“¦

This will enable users to store and retrieve data in a structured format, making it easier to manage and manipulate information within their applications. πŸ› οΈ

Queues (Planned) πŸ“¬

Queues are a planned feature that will allow users to manage tasks and jobs within their applications. πŸ› οΈ

This will enable users to create and manage background jobs, allowing for better performance and scalability within their applications. πŸš€

Secrets (Planned) πŸ”’

Secrets are a planned feature that will allow users to manage sensitive data and secrets within their applications. πŸ›‘οΈ

This will enable users to securely store and manage sensitive information, such as API keys, passwords, and other confidential data. πŸ”‘

This will help ensure that sensitive information is kept secure and is not exposed to unauthorized users. 🚨