Set up a TRAPI web server in 6 lines of Python!
- a fast web server
- optionally asynchronous using asyncio
- auto-generated OpenAPI schema and Swagger UI
- request and response validation
- full TRAPI compliance, guaranteed1
pip install fastapi reasoner-pydantic uvicorn
server.py
:
from fastapi import FastAPI
from reasoner_pydantic import Query, Response
APP = FastAPI(title="TRAPI service")
@APP.post("/query", response_model=Response)
def trapi_operation(query: Query) -> Response:
# perform operation on query.message...
return Response(message=query.message)
Using uvicorn:
uvicorn server:APP --host 0.0.0.0 --port 8080
Go to your Swagger UI at http://localhost:8080/docs
First, we import the FastAPI class and the two top-level TRAPI components: Query and Response.
from fastapi import FastAPI
from reasoner_pydantic import Query, Response
Then we initialize the FastAPI application object.
APP = FastAPI(title="TRAPI service")
The FastAPI.post
decorator declares the decorated function as an API endpoint handler. Here we assign a handler to the /query endpoint, and provide the model for its response.
@APP.post("/query", response_model=Response)
The handler function uses type hints to describe its input and output. The pydantic models can be used directly or can be easily converted to/from dictionaries.
def trapi_operation(query: Query) -> Response:
# perform operation on query.message...
return Response(message=query.message)
- pydantic: "Data validation and settings management using Python type hinting. Fast and extensible, pydantic plays nicely with your linters/IDE/brain. Define how data should be in pure, canonical Python 3.6+; validate it with pydantic."
- FastAPI: "FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints."
- reasoner-pydantic: pydantic models reflecting the TRAPI (v1.0.3) components
Submit questions here.
Submit bug reports here.
For a more complete example using reasoner-pydantic & FastAPI, see filter_results_top_n. This includes:
- OpenAPI request and response examples
- required SmartAPI metadata (
x-translator
, etc.) - Docker-ization