Add an API Route to your App

In order to add a new route, you need to override the configure_api hook and return a list of HttpMethod such as Get, Post, Put, Delete.


1. Create a simple App

We’re going to create a single route /name that takes a string input name and stores the value within the names attribute of the flow state.

Create a file called app.py and copy-paste the following code in to the file:

from lightning.app import LightningFlow, LightningApp
from lightning.app.api import Post


class Flow(LightningFlow):
    # 1. Define the state
    def __init__(self):
        super().__init__()
        self.names = []

    # 2. Optional, but used to validate names
    def run(self):
        print(self.names)

    # 3. Method executed when a request is received.
    def handle_post(self, name: str):
        self.names.append(name)
        return f'The name {name} was registered'

    # 4. Defines this Component's Restful API. You can have several routes.
    def configure_api(self):
        return [Post(route="/name", method=self.handle_post)]


app = LightningApp(Flow())

2. Run the App

Execute the following command in a terminal:

lightning_app run app app.py

The following appears:

Your Lightning App is starting. This won't take long.
INFO: Your app has started. View it in your browser: http://127.0.0.1:7501/view

3. Check the API

The Lightning App framework automatically generates API documentation from your App using Swagger UI.

You can access it by accessing the following URL: http://127.0.0.1:7501/docs in your browser and validate your API with the route /name directly from the documentation page as shown below.

Alternatively, you can invoke the route directly from a second terminal using curl.

curl -X 'POST' \
'http://127.0.0.1:7501/name?name=my_name' \
-H 'accept: application/json' \
-d ''

"The name my_name was registered"

And you can see the following in your first terminal running your App.

Your Lightning App is starting. This won't take long.
INFO: Your app has started. View it in your browser: http://127.0.0.1:7501/view
[]
["my_name"]