a lightweight web framework based on fastapi

Overview

start-fastapi

Version 2021, based on FastAPI, an easy-to-use web app developed upon Starlette Framework

Requirements

  • python 3.6+ (for static typing check)
  • pip3 install -r ./requirements.txt
  • idea/pycharm (recommended) + venv

Structure

The web application is based on onion style~

onion

The directory structure is:

  • app: logics for your application, includes __init__.py as entry of user modules
    • handler: controllers
    • middleware: router middleware, like cors
    • model: basic data models and internal logics
    • service: external logics (to users)
  • cfg: config of different envs
  • core: low level libraries and logics, includes __init__.py as entry of core modules, better make it able to be reused in other projects
    • handler
    • lib: shortcut apis for user to build logics
    • model
    • service
      • trans: transaction service, for managing tasks running in background
  • misc: misc parts, like build, test scripts, etc
    • build: build scripts
    • dev: resources for dev usage
      • gen_code.py: a script for generating codes
    • doc: docs
    • test: test scripts
  • main.py: main entry, init uvicorn and start fastapi app
  • requirements.txt: py package requirements

Quick Start

Launch App Server

Run ./main.py to start the example, which includes:

  • core modules: health check handler, basic models, transaction service
  • cors middleware configured with wildcard *
  • test handlers, models and service: simulates a simple market trade system with products and customers
    • examples of websocket and upload file are also included in test handlers

The internal steps are:

  • ./main.py loads the configs inside ./cfg/{env} on cmd args, then calls uvicorn.run to start fastapi app at ./app/__init__.py
  • in ./app/__init__.py, core modules and user handlers/models/services are loaded at startup event of fastapi app

You can put your launch scripts inside ./misc/build for your different launch options

Coding Guide

To build your logic, common steps are follows:

  • ./main.py runs server in dev environment in default, in which hot-reload is enabled
  • add handlers in ./app/handler, add corresponding import & APP.include_router codes in ./app/__init__.py
  • add data models in ./app/model, add services in ./app/service
  • add middlewares in ./app/middleware if necessary

Some tips for coding:

  • GET /docs to test the routers on web page
  • Avoid using coroutines (async def functions), as it may block the main evtloop, so that other requests are not handled in time. def functions will be invoked in different threads
  • codes of ./core should be shareable (for other projects), codes of ./app should fit with current project
  • You can use ./misc/dev/gen_code.py to generate template codes for handlers, models & services. Exec it with working directory as project root directory
  • Code models based on pydantic.BaseModel, it's powerful

HTTP Response

Most of the handled requests should contain a status code of 200

A simple solution is to use Resp model in ./core/model/handler.py to generate response body for your handlers

{
  "success": bool,
  "message": str,
  "code": IntEnum,
  "data": Any,
}

Use Resp.ok to generate success response and use Resp.err to generate error response

Misc

WebSocket

The test handler ./app/handler/test.py contains ws handler examples

To know more about it, see websocket documentation

Deployment

Run ./misc/build/pack.sh to pack the project into ./misc/build/start-fastapi.tar.gz

See ./misc/build/Dockerfile for an example of docker deployment

You might also like...
FastAPI Learning Example,对应中文视频学习教程:https://space.bilibili.com/396891097

视频教学地址 中文学习教程 1、本教程每一个案例都可以独立跑,前提是安装好依赖包。 2、本教程并未按照官方教程顺序,而是按照实际使用顺序编排。 Video Teaching Address FastAPI Learning Example 1.Each case in this tutorial c

🤪 FastAPI + Vue构建的Mall项目后台管理

Mall项目后台管理 前段时间学习Vue写了一个移动端项目 https://www.charmcode.cn/app/mall/home 然后教程到此就结束了, 我就总感觉少点什么,计划自己着手写一套后台管理。 相关项目 移动端Mall项目源码(Vue构建): https://github.com/

Backend, modern REST API for obtaining match and odds data crawled from multiple sites. Using FastAPI, MongoDB as database, Motor as async MongoDB client, Scrapy as crawler and Docker.
Backend, modern REST API for obtaining match and odds data crawled from multiple sites. Using FastAPI, MongoDB as database, Motor as async MongoDB client, Scrapy as crawler and Docker.

Introduction Apiestas is a project composed of a backend powered by the awesome framework FastAPI and a crawler powered by Scrapy. This project has fo

Backend Skeleton using FastAPI and Sqlalchemy ORM

Backend API Skeleton Based on @tiangolo's full stack postgres template, with some things added, some things removed, and some things changed. This is

FastAPI on Google Cloud Run

cloudrun-fastapi Boilerplate for running FastAPI on Google Cloud Run with Google Cloud Build for deployment. For all documentation visit the docs fold

FastAPI + Django experiment

django-fastapi-example This is an experiment to demonstrate one potential way of running FastAPI with Django. It won't be actively maintained. If you'

Auth for use with FastAPI

FastAPI Auth Pluggable auth for use with FastAPI Supports OAuth2 Password Flow Uses JWT access and refresh tokens 100% mypy and test coverage Supports

FastAPI Boilerplate

FastAPI Boilerplate Features SQlAlchemy session Custom user class Top-level dependency Dependencies for specific permissions Celery SQLAlchemy for asy

Minimal example utilizing fastapi and celery with RabbitMQ for task queue, Redis for celery backend and flower for monitoring the celery tasks.

FastAPI with Celery Minimal example utilizing FastAPI and Celery with RabbitMQ for task queue, Redis for Celery backend and flower for monitoring the

Comments
  • Bump pydantic from 1.7.3 to 1.7.4

    Bump pydantic from 1.7.3 to 1.7.4

    Bumps pydantic from 1.7.3 to 1.7.4.

    Release notes

    Sourced from pydantic's releases.

    v1.7.4 (2021-05-11)

    Security fix: Fix date and datetime parsing so passing either 'infinity' or float('inf') (or their negative values) does not cause an infinite loop, see security advisory CVE-2021-29510.

    Changelog

    Sourced from pydantic's changelog.

    v1.7.4 (2021-05-11)

    • Security fix: Fix date and datetime parsing so passing either 'infinity' or float('inf') (or their negative values) does not cause an infinite loop, See security advisory CVE-2021-29510
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Bump uvicorn from 0.11.5 to 0.11.7

    Bump uvicorn from 0.11.5 to 0.11.7

    Bumps uvicorn from 0.11.5 to 0.11.7.

    Release notes

    Sourced from uvicorn's releases.

    Version 0.11.7

    0.11.7

    • SECURITY FIX: Prevent sending invalid HTTP header names and values.
    • SECURITY FIX: Ensure path value is escaped before logging to the console.

    Version 0.11.6

    • Fix overriding the root logger.
    Changelog

    Sourced from uvicorn's changelog.

    0.11.7

    • SECURITY FIX: Prevent sending invalid HTTP header names and values.
    • SECURITY FIX: Ensure path value is escaped before logging to the console.

    0.11.6

    • Fix overriding the root logger.
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Bump websockets from 8.1 to 9.1

    Bump websockets from 8.1 to 9.1

    Bumps websockets from 8.1 to 9.1.

    Changelog

    Sourced from websockets's changelog.

    9.1 ...

    May 27, 2021

    .. note::

    **Version 9.1 fixes a security issue introduced in version 8.0.**
    

    Version 8.0 was vulnerable to timing attacks on HTTP Basic Auth passwords.

    9.0.2 .....

    May 15, 2021

    • Restored compatibility of python -m websockets with Python < 3.9.

    • Restored compatibility with mypy.

    9.0.1 .....

    May 2, 2021

    • Fixed issues with the packaging of the 9.0 release.

    9.0 ...

    May 1, 2021

    .. note::

    **Version 9.0 moves or deprecates several APIs.**
    

    Aliases provide backwards compatibility for all previously public APIs.

    • :class:~datastructures.Headers and :exc:~datastructures.MultipleValuesError were moved from websockets.http to :mod:websockets.datastructures. If you're using them, you should adjust the import path.

    • The client, server, protocol, and auth modules were moved from the websockets package to websockets.legacy sub-package, as part of an upcoming refactoring. Despite the name, they're still fully supported. The refactoring should be a transparent upgrade for most uses when it's available. The legacy implementation will be preserved according to the backwards-compatibility policy_.

... (truncated)

Commits
  • d0f3288 Bump version number.
  • 547a26b Use constant-time comparison for passwords.
  • a14226a Bump version number.
  • 8900c13 Add mypy to dictionary.
  • 0713dbf Add test coverage.
  • b99c4fe Restore real imports for compatibility with mypy.
  • e44e085 Use relative imports everywhere, for consistency.
  • 70fadbf Restore compatibility with Python < 3.9.
  • 217ac2d Fix broken link.
  • fc176f4 Bump version number.
  • Additional commits viewable in compare view

Dependabot compatibility score

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


Dependabot commands and options

You can trigger Dependabot actions by commenting on this PR:

  • @dependabot rebase will rebase this PR
  • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
  • @dependabot merge will merge this PR after your CI passes on it
  • @dependabot squash and merge will squash and merge this PR after your CI passes on it
  • @dependabot cancel merge will cancel a previously requested merge and block automerging
  • @dependabot reopen will reopen this PR if it is closed
  • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
  • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
  • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
  • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
  • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
  • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

You can disable automated security fix PRs for this repo from the Security Alerts page.

dependencies 
opened by dependabot[bot] 0
  • Bump fastapi from 0.65.1 to 0.65.2

    Bump fastapi from 0.65.1 to 0.65.2

    Bumps fastapi from 0.65.1 to 0.65.2.

    Release notes

    Sourced from fastapi's releases.

    0.65.2

    Security fixes

    This change fixes a CSRF security vulnerability when using cookies for authentication in path operations with JSON payloads sent by browsers.

    In versions lower than 0.65.2, FastAPI would try to read the request payload as JSON even if the content-type header sent was not set to application/json or a compatible JSON media type (e.g. application/geo+json).

    So, a request with a content type of text/plain containing JSON data would be accepted and the JSON data would be extracted.

    But requests with content type text/plain are exempt from CORS preflights, for being considered Simple requests. So, the browser would execute them right away including cookies, and the text content could be a JSON string that would be parsed and accepted by the FastAPI application.

    See CVE-2021-32677 for more details.

    Thanks to Dima Boger for the security report! 🙇🔒

    Internal

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Releases(v2020)
    Owner
    HiKari
    Game QA Tools & Infra
    HiKari
    The template for building scalable web APIs based on FastAPI, Tortoise ORM and other.

    FastAPI and Tortoise ORM. Powerful but simple template for web APIs w/ FastAPI (as web framework) and Tortoise-ORM (for working via database without h

    prostomarkeloff 95 Jan 8, 2023
    api versioning for fastapi web applications

    fastapi-versioning api versioning for fastapi web applications Installation pip install fastapi-versioning Examples from fastapi import FastAPI from f

    Dean Way 472 Jan 2, 2023
    更新 2.0 版本,使用 Python WEB 高性能异步框架 FastAPI 制作的抖音无水印解析下载,采用前后端分离思想!

    前言 这个是 2.0 版本,使用现在流行的前后端分离思想重构。 体验网址:https://douyin.bigdataboy.cn 更新日志 2020.05.30:使用 FastAPI 前后端分离重构 2020.05.02:已更新,正常使用 2020.04.27:抖音结构更新,已修复视频有水印。(失

    null 64 Nov 25, 2022
    sample web application built with FastAPI + uvicorn

    SPARKY Sample web application built with FastAPI & Python 3.8 shows simple Flask-like structure with a Bootstrap template index.html also has a backgr

    mrx 21 Jan 3, 2022
    row level security for FastAPI framework

    Row Level Permissions for FastAPI While trying out the excellent FastApi framework there was one peace missing for me: an easy, declarative way to def

    Holger Frey 315 Dec 25, 2022
    FastAPI framework plugins

    Plugins for FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi-plugins FastAPI framework plugins Cache Mem

    RES 239 Dec 28, 2022
    TODO aplication made with Python's FastAPI framework and Hexagonal Architecture

    FastAPI Todolist Description Todolist aplication made with Python's FastAPI framework and Hexagonal Architecture. This is a test repository for the pu

    Giovanni Armane 91 Dec 31, 2022
    JSON-RPC server based on fastapi

    Description JSON-RPC server based on fastapi: https://fastapi.tiangolo.com Motivation Autogenerated OpenAPI and Swagger (thanks to fastapi) for JSON-R

    null 199 Dec 30, 2022
    A Jupyter server based on FastAPI (Experimental)

    jupyverse is experimental and should not be used in place of jupyter-server, which is the official Jupyter server.

    Jupyter Server 122 Dec 27, 2022
    Example app using FastAPI and JWT

    FastAPI-Auth Example app using FastAPI and JWT virtualenv -p python3 venv source venv/bin/activate pip3 install -r requirements.txt mv config.yaml.exa

    Sander 28 Oct 25, 2022