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
    A minimalistic example of preparing a model for (synchronous) inference in production.

    A minimalistic example of preparing a model for (synchronous) inference in production.

    Anton Lozhkov 6 Nov 29, 2021
    Money Transaction is a system based on the recent famous FastAPI.

    moneyTransfer Overview Money Transaction is a system based on the recent famous FastAPI. techniques selection System's technique selection is as follo

    2 Apr 28, 2021
    a lightweight web framework based on fastapi

    start-fastapi Version 2021, based on FastAPI, an easy-to-use web app developed upon Starlette Framework Version 2020 中文文档 Requirements python 3.6+ (fo

    HiKari 71 Dec 30, 2022
    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 02, 2023
    Online Repo Browser

    MSYS2 Web Interface A simple web interface for browsing the MSYS2 repos. Rebuild CSS/JS (optional): cd frontend npm install npm run build Run for Dev

    MSYS2 64 Dec 30, 2022
    Publish Xarray Datasets via a REST API.

    Xpublish Publish Xarray Datasets via a REST API. Serverside: Publish a Xarray Dataset through a rest API ds.rest.serve(host="0.0.0.0", port=9000) Clie

    xarray-contrib 106 Jan 06, 2023
    Web Inventory tool, takes screenshots of webpages using Pyppeteer (headless Chrome/Chromium) and provides some extra bells & whistles to make life easier.

    WitnessMe WitnessMe is primarily a Web Inventory tool inspired by Eyewitness, its also written to be extensible allowing you to create custom function

    byt3bl33d3r 648 Jan 05, 2023
    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'

    Jordan Eremieff 78 Jan 03, 2023
    📦 Autowiring dependency injection container for python 3

    Lagom - Dependency injection container What Lagom is a dependency injection container designed to give you "just enough" help with building your depen

    Steve B 146 Dec 29, 2022
    Recommend recipes based on what ingredients you have at home

    🌱 MyChef 📦 Overview MyChef is an application that helps you decide what meal to make based on what you have at home. Simply enter in ingredients you

    Logan Connolly 44 Nov 08, 2022
    [rewrite 중] 코로나바이러스감염증-19(COVID-19)의 국내/국외 발생 동향 조회 API | Coronavirus Infectious Disease-19 (COVID-19) outbreak trend inquiry API

    COVID-19API 코로나 바이러스 감염증-19(COVID-19, SARS-CoV-2)의 국내/외 발생 동향 조회 API Corona Virus Infectious Disease-19 (COVID-19, SARS-CoV-2) outbreak trend inquiry

    Euiseo Cha 28 Oct 29, 2022
    更新 2.0 版本,使用 Python WEB 高性能异步框架 FastAPI 制作的抖音无水印解析下载,采用前后端分离思想!

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

    64 Nov 25, 2022
    Web Version of avatarify to democratize even further

    Web-avatarify for image animations This is the code base for this website and its backend. This aims to bring technology closer to everyone, just by a

    Carlos Andrés Álvarez Restrepo 66 Nov 09, 2022
    asgi-server-timing-middleware

    ASGI Server-Timing middleware An ASGI middleware that wraps the excellent yappi profiler to let you measure the execution time of any function or coro

    33 Dec 15, 2022
    官方文档已经有翻译的人在做了,

    FastAPI 框架,高性能,易学,快速编码,随时可供生产 文档:https://fastapi.tiangolo.com 源码:https://github.com/tiangolo/fastapi FastAPI 是一个现代、快速(高性能)的 Web 框架,基于标准 Python 类型提示,使用

    ApacheCN 27 Nov 11, 2022
    ReST based network device broker

    The Open API Platform for Network Devices netpalm makes it easy to push and pull state from your apps to your network by providing multiple southbound

    368 Dec 31, 2022
    ASGI middleware for authentication, rate limiting, and building CRUD endpoints.

    Piccolo API Utilities for easily exposing Piccolo models as REST endpoints in ASGI apps, such as Starlette and FastAPI. Includes a bunch of useful ASG

    81 Dec 09, 2022
    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

    David Montague 18 Oct 31, 2022
    python fastapi example connection to mysql

    Quickstart Then run the following commands to bootstrap your environment with poetry: git clone https://github.com/xiaozl/fastapi-realworld-example-ap

    55 Dec 15, 2022
    Lung Segmentation with fastapi

    Lung Segmentation with fastapi This app uses FastAPI as backend. Usage for app.py First install required libraries by running: pip install -r requirem

    Pejman Samadi 0 Sep 20, 2022