Add Requests Validation¶
The Lightning App framework uses the popular FastAPI and Pydantic frameworks under the hood. This means you can use all their features while building your App.
pydantic enables fast data validation and settings management using Python type annotations and FastAPI is a modern, fast (high-performance), web framework for building APIs.
You can easily use pydantic by defining your own payload format.
from pydantic import BaseModel
# 1. Subclass the BaseModel and defines your payload format.
class NamePostConfig(BaseModel):
name: str
Then, type your handler input with your custom model.
from models import NamePostConfig # 2. Import your custom model.
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. Annotate your input with your custom pydantic model.
def handle_post(self, config: NamePostConfig):
self.names.append(config.name)
return f'The name {config} 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())
After running the updated App, the App documentation /name
has changed and takes JSON with {"name": ...}
as input.
You can invoke the RESTful API route /name
with the following command:
curl -X 'POST' \
'http://127.0.0.1:7501/name' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "my_name"
}'
Note
Using curl, you can pass a JSON payload using the -d
argument.