by davi
Backend Server
import logging
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from abilities import apply_sqlite_migrations
from models import Base, engine
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
@app.get("/", include_in_schema=False)
def root():
return RedirectResponse(url="/docs")
@app.get("/list")
def list_entrypoint():
some_list = ["data1", "data2"]
return some_list
Frequently Asked Questions
What types of applications is this Backend Server template best suited for?
The Backend Server template is ideal for building microservices, RESTful APIs, and backend services with minimal frontend requirements. It's particularly well-suited for projects that need fast, efficient, and scalable backend solutions. For example, you could use this template to create a data processing service, a content management system API, or a backend for a mobile application.
How does this Backend Server template improve development efficiency?
This template significantly improves development efficiency by providing a pre-configured FastAPI setup with essential components like database migrations, logging, and a basic project structure. It allows developers to focus on implementing business logic rather than spending time on boilerplate code. The Backend Server template also includes a ready-to-use Docker configuration, making it easier to deploy and scale your application.
Can the Backend Server template be used for enterprise-level applications?
Absolutely. The Backend Server template is built on FastAPI, which is known for its performance and scalability, making it suitable for enterprise-level applications. The template includes features like database migrations and structured request handlers, which are essential for maintaining and scaling large-scale applications. However, for enterprise use, you may need to extend the template with additional security features, authentication mechanisms, and more complex database models.
How can I add a new endpoint to the Backend Server template?
To add a new endpoint to the Backend Server template, you can create a new function in either main.py
or a separate file, and decorate it with the appropriate FastAPI decorator. Here's an example of adding a new GET endpoint:
```python from fastapi import FastAPI
app = FastAPI()
@app.get("/new-endpoint") def new_endpoint(): return {"message": "This is a new endpoint"} ```
If you're adding the endpoint in a separate file, make sure to import and include it in main.py
.
How does the Backend Server template handle database migrations?
The Backend Server template uses SQL scripts for database migrations. These scripts are stored in the migrations
directory and are applied automatically when the application starts. To add a new migration, create a new SQL file in the migrations
directory with a name starting with a number (e.g., 001_create_users_table.sql
). Here's an example of a migration script:
sql
-- 001_create_users_table.sql
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL
);
The apply_sqlite_migrations
function in the template will execute these scripts in order when the application starts, ensuring your database schema stays up-to-date.
Created: | Last Updated:
Here's a step-by-step guide on how to use the provided FastAPI backend server template:
Introduction
This template provides a streamlined skeleton for creating backend services using FastAPI. It's an excellent choice for building microservices or APIs with minimal frontend requirements.
Getting Started
- Click "Start with this Template" to begin using this FastAPI backend server template in the Lazy Builder interface.
Test the Application
- Press the "Test" button to start the deployment process. This will launch the Lazy CLI and begin the server initialization.
Using the App
- Once the deployment is complete, you'll receive two important links through the Lazy builder CLI:
- An API link to interact with your server
-
A documentation link (usually ending with
/docs
) to explore the API endpoints -
Open the documentation link in your web browser. This will take you to the FastAPI automatic interactive API documentation (Swagger UI).
-
In the Swagger UI, you'll see two endpoints:
/
: This is the root endpoint, which redirects to the/docs
page.-
/list
: This endpoint returns a list of sample data. -
You can test the
/list
endpoint directly from the Swagger UI by clicking on it, then clicking the "Try it out" button, and finally "Execute". You should see a response containing["data1", "data2"]
.
Customizing the App
- To add new endpoints or modify existing ones, you can update the
main.py
file. For example, to add a new GET endpoint:
```python from some_get_request_handler import handle_get_endpoint
@app.get("/new-endpoint") def new_endpoint(): return handle_get_endpoint() ```
- To add a POST endpoint that accepts data:
```python from some_post_request_handler import handle_post_endpoint, Data
@app.post("/post-endpoint") def post_endpoint(data: Data): return handle_post_endpoint(data) ```
- If you need to add new database models, update the
models.py
file:
```python from sqlalchemy import Column, Integer, String
class NewModel(Base): tablename = "new_table" id = Column(Integer, primary_key=True, index=True) name = Column(String, unique=True, index=True) ```
- To apply database migrations, create new SQL files in the
migrations
folder, starting with001_*.sql
,002_*.sql
, and so on.
Integrating the App
This FastAPI backend can be integrated with various frontend frameworks or other services that need to consume APIs. To integrate it:
-
Use the API link provided by the Lazy builder CLI as the base URL for your API requests.
-
Make HTTP requests to the appropriate endpoints. For example, to get the list of data:
```python import requests
response = requests.get("https://your-api-link.lazy-app.com/list") data = response.json() print(data) ```
- For POST requests, ensure you send the correct data structure. For example:
```python import requests
data = {"field": "some value"} response = requests.post("https://your-api-link.lazy-app.com/post-endpoint", json=data) result = response.json() print(result) ```
Remember to replace "https://your-api-link.lazy-app.com"
with the actual API link provided by the Lazy builder CLI.
By following these steps, you can effectively use and customize this FastAPI backend server template to create robust and scalable backend services.
Template Benefits
-
Rapid API Development: This FastAPI-based template allows for quick and efficient development of RESTful APIs, enabling businesses to rapidly prototype and deploy backend services.
-
Scalable Microservices Architecture: The structure is ideal for building microservices, allowing companies to develop modular, easily maintainable, and scalable backend systems.
-
Automatic Documentation: FastAPI's built-in Swagger UI (/docs endpoint) provides automatic, interactive API documentation, reducing the time and effort needed for creating and maintaining API documentation.
-
Database Integration Ready: With SQLAlchemy and migration support included, the template facilitates easy database integration and management, crucial for data-driven applications.
-
Production-Ready Setup: The inclusion of Uvicorn server and proper logging configuration makes this template ready for production deployment, reducing the time from development to launch.