by davi

Backend Server

Test this app for free
24
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
Get full code

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:

This skeleton is streamlined for creating backend services using FastAPI. It's an excellent choice for building microservices or APIs with minimal frontend requirements.

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

  1. Click "Start with this Template" to begin using this FastAPI backend server template in the Lazy Builder interface.

Test the Application

  1. Press the "Test" button to start the deployment process. This will launch the Lazy CLI and begin the server initialization.

Using the App

  1. Once the deployment is complete, you'll receive two important links through the Lazy builder CLI:
  2. An API link to interact with your server
  3. A documentation link (usually ending with /docs) to explore the API endpoints

  4. Open the documentation link in your web browser. This will take you to the FastAPI automatic interactive API documentation (Swagger UI).

  5. In the Swagger UI, you'll see two endpoints:

  6. /: This is the root endpoint, which redirects to the /docs page.
  7. /list: This endpoint returns a list of sample data.

  8. 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

  1. 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() ```

  1. 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) ```

  1. 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) ```

  1. To apply database migrations, create new SQL files in the migrations folder, starting with 001_*.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:

  1. Use the API link provided by the Lazy builder CLI as the base URL for your API requests.

  2. 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) ```

  1. 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

  1. 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.

  2. Scalable Microservices Architecture: The structure is ideal for building microservices, allowing companies to develop modular, easily maintainable, and scalable backend systems.

  3. 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.

  4. Database Integration Ready: With SQLAlchemy and migration support included, the template facilitates easy database integration and management, crucial for data-driven applications.

  5. 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.

Technologies

FastAPI Templates and Webhooks FastAPI Templates and Webhooks

Similar templates

FastAPI endpoint for Text Classification using OpenAI GPT 4

This API will classify incoming text items into categories using the Open AI's GPT 4 model. If the model is unsure about the category of a text item, it will respond with an empty string. The categories are parameters that the API endpoint accepts. The GPT 4 model will classify the items on its own with a prompt like this: "Classify the following item {item} into one of these categories {categories}". There is no maximum number of categories a text item can belong to in the multiple categories classification. The API will use the llm_prompt ability to ask the LLM to classify the item and respond with the category. The API will take the LLM's response as is and will not handle situations where the model identifies multiple categories for a text item in the single category classification. If the model is unsure about the category of a text item in the multiple categories classification, it will respond with an empty string for that item. The API will use Python's concurrent.futures module to parallelize the classification of text items. The API will handle timeouts and exceptions by leaving the items unclassified. The API will parse the LLM's response for the multiple categories classification and match it to the list of categories provided in the API parameters. The API will convert the LLM's response and the categories to lowercase before matching them. The API will split the LLM's response on both ':' and ',' to remove the "Category" word from the response. The temperature of the GPT model is set to a minimal value to make the output more deterministic. The API will return all matching categories for a text item in the multiple categories classification. The API will strip any leading or trailing whitespace from the categories in the LLM's response before matching them to the list of categories provided in the API parameters. The API will accept lists as answers from the LLM. If the LLM responds with a string that's formatted like a list, the API will parse it and match it to the list of categories provided in the API parameters.

Icon 1 Icon 1
218

We found some blogs you might like...