当前位置: 首页 > article >正文

fastapi · FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi · FastAPI framework, high performance, easy to learn, fast to code, ready for production本文整理自 GitHub经重新整理编辑。FastAPI framework, high performance, easy to learn, fast to code, ready for productionDocumentation: https://fastapi.tiangolo.comSource Code: https://github.com/fastapi/fastapiFastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.The key features are:Fast: Very high performance, on par withNodeJSandGo(thanks to Starlette and Pydantic). One of the fastest Python frameworks available.Fast to code: Increase the speed to develop features by about 200% to 300%. *Fewer bugs: Reduce about 40% of human (developer) induced errors. *Intuitive: Great editor support.Completioneverywhere. Less time debugging.Easy: Designed to be easy to use and learn. Less time reading docs.Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.Robust: Get production-ready code. With automatic interactive documentation.Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.* estimation based on tests conducted by an internal development team, building production applications.SponsorsKeystone SponsorGold SponsorsSilver SponsorsOther sponsorsOpinions“[…] I’m usingFastAPIa ton these days. […] I’m actually planning to use it for all of my team’sML services at Microsoft. Some of them are getting integrated into the coreWindowsproduct and someOfficeproducts.”Kabir Khan -Microsoft(ref)“We adopted theFastAPIlibrary to spawn aRESTserver that can be queried to obtainpredictions. [for Ludwig]”Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala -Uber(ref)“Netflixis pleased to announce the open-source release of ourcrisis managementorchestration framework:Dispatch! [built withFastAPI]”Kevin Glisson, Marc Vilanova, Forest Monsen -Netflix(ref)“If anyone is looking to build a production Python API, I would highly recommendFastAPI. It isbeautifully designed,simple to useandhighly scalable, it has become akey componentin our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer.”Deon Pillsbury -Cisco(ref)FastAPI ConfFastAPI Conf 26is happening onOctober 28, 2026inAmsterdam, NL. All about FastAPI, right from the source. FastAPI mini documentaryThere’s a FastAPI mini documentary released at the end of 2025, you can watch it online:Typer, the FastAPI of CLIsIf you are building a CLIapp to be used in the terminal instead of a web API, check outTyper.Typeris FastAPI’s little sibling. And it’s intended to be theFastAPI of CLIs. ⌨️ RequirementsFastAPI stands on the shoulders of giants:Starlette for the web parts.Pydantic for the data parts.InstallationCreate and activate a virtual environment and then install FastAPI:$ pip install fastapi[standard] --- 100%Note: Make sure you putfastapi[standard]in quotes to ensure it works in all terminals.ExampleCreate itCreate a filemain.pywith:from fastapi import FastAPI app FastAPI() app.get(/) def read_root(): return {Hello: World} app.get(/items/{item_id}) def read_item(item_id: int, q: str | None None): return {item_id: item_id, q: q}Or useasync def...If your code usesasync/await, useasync def:from fastapi import FastAPI app FastAPI() app.get(/) async def read_root(): return {Hello: World} app.get(/items/{item_id}) async def read_item(item_id: int, q: str | None None): return {item_id: item_id, q: q}Note:If you don’t know, check the“In a hurry?”section aboutasyncandawaitin the docs.Run itRun the server with:$ fastapi dev ╭────────── FastAPI CLI - Development mode ───────────╮ │ │ │ Serving at: http://127.0.0.1:8000 │ │ │ │ API docs: http://127.0.0.1:8000/docs │ │ │ │ Running in development mode, for production use: │ │ │ │ fastapi run │ │ │ ╰─────────────────────────────────────────────────────╯ INFO: Will watch for changes in these directories: [/home/user/code/awesomeapp] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRLC to quit) INFO: Started reloader process [2248755] using WatchFiles INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete.About the commandfastapi dev...The commandfastapi devreads yourmain.pyfile automatically, detects theFastAPIapp in it, and starts a server using Uvicorn.By default,fastapi devwill start with auto-reload enabled for local development.You can read more about it in the FastAPI CLI docs.Check itOpen your browser at http://127.0.0.1:8000/items/5?qsomequery.You will see the JSON response as:{item_id: 5, q: somequery}You already created an API that:Receives HTTP requests in thepaths/and/items/{item_id}.BothpathstakeGEToperations(also known as HTTPmethods).Thepath/items/{item_id}has apath parameteritem_idthat should be anint.Thepath/items/{item_id}has an optionalstrquery parameterq.Interactive API docsNow go to http://127.0.0.1:8000/docs.You will see the automatic interactive API documentation (provided by Swagger UI):[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a9hmlAeb-1779376834056)(https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)]Alternative API docsAnd now, go to http://127.0.0.1:8000/redoc.You will see the alternative automatic documentation (provided by ReDoc):[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tVuDH7YS-1779376834057)(https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)]Example upgradeNow modify the filemain.pyto receive a body from aPUTrequest.Declare the body using standard Python types, thanks to Pydantic.from fastapi import FastAPI from pydantic import BaseModel app FastAPI() class Item(BaseModel): name: str price: float is_offer: bool | None None app.get(/) def read_root(): return {Hello: World} app.get(/items/{item_id}) def read_item(item_id: int, q: str | None None): return {item_id: item_id, q: q} app.put(/items/{item_id}) def update_item(item_id: int, item: Item): return {item_name: item.name, item_id: item_id}Thefastapi devserver should reload automatically.Interactive API docs upgradeNow go to http://127.0.0.1:8000/docs.The interactive API documentation will be automatically updated, including the new body:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qmPaz3BR-1779376834057)(https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)]Click on the button “Try it out”, it allows you to fill the parameters and directly interact with the API:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-giRciojw-1779376834057)(https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)]Then click on the “Execute” button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3N7ucuha-1779376834057)(https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)]Alternative API docs upgradeAnd now, go to http://127.0.0.1:8000/redoc.The alternative documentation will also reflect the new query parameter and body:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VlAOyXOE-1779376834058)(https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)]RecapIn summary, you declareoncethe types of parameters, body, etc. as function parameters.You do that with standard modern Python types.You don’t have to learn a new syntax, the methods or classes of a specific library, etc.Just standardPython.For example, for anint:item_id: intor for a more complexItemmodel:item: Item…and with that single declaration you get:Editor support, including:Completion.Type checks.Validation of data:Automatic and clear errors when the data is invalid.Validation even for deeply nested JSON objects.Conversionof input data: coming from the network to Python data and types. Reading from:JSON.Path parameters.Query parameters.Cookies.Headers.Forms.Files.Conversionof output data: converting from Python data and types to network data (as JSON):Convert Python types (str,int,float,bool,list, etc).datetimeobjects.UUIDobjects.Database models.…and many more.Automatic interactive API documentation, including 2 alternative user interfaces:Swagger UI.ReDoc.Coming back to the previous code example,FastAPIwill:Validate that there is anitem_idin the path forGETandPUTrequests.Validate that theitem_idis of typeintforGETandPUTrequests.If it is not, the client will see a useful, clear error.Check if there is an optional query parameter namedq(as inhttp://127.0.0.1:8000/items/foo?qsomequery) forGETrequests.As theqparameter is declared with None, it is optional.Without theNoneit would be required (as is the body in the case withPUT).ForPUTrequests to/items/{item_id}, read the body as JSON:Check that it has a required attributenamethat should be astr.Check that it has a required attributepricethat has to be afloat.Check that it has an optional attributeis_offer, that should be abool, if present.All this would also work for deeply nested JSON objects.Convert from and to JSON automatically.Document everything with OpenAPI, that can be used by:Interactive documentation systems.Automatic client code generation systems, for many languages.Provide 2 interactive documentation web interfaces directly.We just scratched the surface, but you already get the idea of how it all works.Try changing the line with:return {item_name: item.name, item_id: item_id}…from:... item_name: item.name ...…to:... item_price: item.price ...…and see how your editor will auto-complete the attributes and know their types:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LKopHHVz-1779376834058)(https://fastapi.tiangolo.com/img/vscode-completion.png)]For a more complete example including more features, see the Tutorial - User Guide.Spoiler alert: the tutorial - user guide includes:Declaration ofparametersfrom other different places as:headers,cookies,form fieldsandfiles.How to setvalidation constraintsasmaximum_lengthorregex.A very powerful and easy to useDependency Injectionsystem.Security and authentication, including support forOAuth2withJWT tokensandHTTP Basicauth.More advanced (but equally easy) techniques for declaringdeeply nested JSON models(thanks to Pydantic).GraphQLintegration with Strawberry and other libraries.Many extra features (thanks to Starlette) as:WebSocketsextremely easy tests based on HTTPX andpytestCORSCookie Sessions…and more.Deploy your app (optional)You can optionally deploy your FastAPI app to FastAPI Cloud, go and join the waiting list if you haven’t. If you already have aFastAPI Cloudaccount (we invited you from the waiting list ), you can deploy your application with one command.$ fastapi deploy Deploying to FastAPI Cloud... ✅ Deployment successful! Ready the chicken! Your app is ready at https://myapp.fastapicloud.devThat’s it! Now you can access your app at that URL. ✨About FastAPI CloudFastAPI Cloudis built by the same author and team behindFastAPI.It streamlines the process ofbuilding,deploying, andaccessingan API with minimal effort.It brings the samedeveloper experienceof building apps with FastAPI todeployingthem to the cloud. FastAPI Cloud is the primary sponsor and funding provider for theFastAPI and friendsopen source projects. ✨Deploy to other cloud providersFastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose.Follow your cloud provider’s guides to deploy FastAPI apps with them. PerformanceIndependent TechEmpower benchmarks showFastAPIapplications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)To understand more about it, see the section Benchmarks.DependenciesFastAPI depends on Pydantic and Starlette.standardDependenciesWhen you install FastAPI withpip install fastapi[standard]it comes with thestandardgroup of optional dependencies:Used by Pydantic:email-validator- for email validation.Used by Starlette:httpx- Required if you want to use theTestClient.jinja2- Required if you want to use the default template configuration.python-multipart- Required if you want to support form“parsing”, withrequest.form().Used by FastAPI:uvicorn- for the server that loads and serves your application. This includesuvicorn[standard], which includes some dependencies (e.g.uvloop) needed for high performance serving.fastapi-cli[standard]- to provide thefastapicommand.This includesfastapi-cloud-cli, which allows you to deploy your FastAPI application to FastAPI Cloud.WithoutstandardDependenciesIf you don’t want to include thestandardoptional dependencies, you can install withpip install fastapiinstead ofpip install fastapi[standard].Withoutfastapi-cloud-cliIf you want to install FastAPI with the standard dependencies but without thefastapi-cloud-cli, you can install withpip install fastapi[standard-no-fastapi-cloud-cli].Additional Optional DependenciesThere are some additional dependencies you might want to install.Additional optional Pydantic dependencies:pydantic-settings- for settings management.pydantic-extra-types- for extra types to be used with Pydantic.Additional optional FastAPI dependencies:orjson- Required if you want to useORJSONResponse.ujson- Required if you want to useUJSONResponse.LicenseThis project is licensed under the terms of the MIT license.欢迎交流讨论共同进步。

相关文章:

fastapi · FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi FastAPI framework, high performance, easy to learn, fast to code, ready for production 本文整理自 GitHub,经重新整理编辑。 FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fas…...

抖音获客失效?拆解本地商家流量困局的底层逻辑与破局路径

一、一个反直觉的数据先看两组数据,它们指向同一个方向。第一组:2025年,抖音本地生活服务GMV突破8500亿元。同期,入驻商家达到1519.8万家动销门店,399万新商家在一年内涌入。第二组:2026年Q1,抖…...

2026年JAVA语言前端还可以学吗?是否还能找到好工作?

因为Java并不是前端语言。前端开发主要用的是 HTML、CSS、JavaScript/TypeScript,以及 React、Vue 等框架。可能您是混淆了 Java 和 JavaScript,或者想问的是“学 Java 还能找到好工作吗?前端还能学吗?” 下面我分开讲清楚&#x…...

【芯片测试】:自定义波形与条件波形

第四篇:进阶篇(上)—— 用户自定义波形与条件波形 系列:《VCDSTIL 实战:从仿真波形到 ATE 测试向量》第 4 篇(共 5 篇) 前言 前三篇介绍的都是 VCDSTIL 的"自动提取"模式&#xff1a…...

在线网盘系统:基于 Spring Boot 的文件存储、分类管理与分享预览实践

在线网盘系统:基于 Spring Boot 的文件存储、分类管理与分享预览实践 项目概述 在线网盘系统的核心目标,是把“文件存储”升级为“文件管理 文件预览 文件分享”的一体化平台。相比只支持上传下载的简易文件系统,这个项目进一步补齐了分类管…...

软考中级《嵌入式系统设计师》全套备考资料(真题 + 教材 + 笔记)

大家好,今天给大家分享一份软考中级「嵌入式系统设计师」的完整备考资料包,从教材、真题到高频笔记全配齐,帮你省去整理资料的时间,直接进入高效备考状态! 📁 资料清单 这套资料覆盖了嵌入式系统设计师备考…...

2026毕业答辩PPT模板实测:三个平台的真实体验与避坑建议

又到毕业答辩季,不少同学论文写完了,却被PPT卡住:排版乱、配色杂、结构不清,明明内容扎实,呈现效果却大打折扣。作为经常接触办公工具的博主,我实测了几个常见的PPT模板与制作平台,重点针对本科…...

【多通道滤波】基于最小均方(McFxLMS)算法用于自适应多通道有源噪声控制(MCANC)应用研究(Matlab代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 ⛳️座右铭&a…...

3步实现百度网盘高速下载:Python解析工具实战指南

3步实现百度网盘高速下载:Python解析工具实战指南 【免费下载链接】baidu-wangpan-parse 获取百度网盘分享文件的下载地址 项目地址: https://gitcode.com/gh_mirrors/ba/baidu-wangpan-parse baidu-wangpan-parse是一款高效的Python工具,专门用于…...

ascend-transformer-boost:Transformer加速库架构原理剖析

前言 我第一次在昇腾NPU上跑Llama-2-7B推理时,用的是PyTorch原生实现,跑出来的吞吐是18 tokens/s,跟官方宣称的29 tokens/s差了快一倍。翻了一圈文档,发现昇腾CANN其实自带了一个Transformer加速库——ascend-transformer-boost&a…...

离散几何拓扑数论(终稿·全定义完整版一)

离散几何拓扑数论(终稿全定义完整版) 作者:乖乖数学 日期:2026 年 5 月 21 日 体系:离散几何拓扑数论( Discrete Geometric Topological Number Theory)...

1987年5月15日中午11-13点出生性格、运势和命运

人们常常对“出生时辰”怀有神秘的好奇,但从现代科学的角度看,出生时间对个体的影响并非玄学,而是可以找到生理学和心理学依据的。1987年4月24日晚上23点到24点之间出生,这个时间点恰好处在夜晚向深夜过渡的时段。抛开任何命理说法…...

1987年6月27日下午13-15点出生性格、运势和命运

1987年6月17日,下午15点到17点之间,正值盛夏时节,阳光炽烈而漫长。这一天出生的孩子,是中国改革开放后“黄金十年”中诞生的又一批弄潮儿。他们的成长轨迹,与全球化浪潮的涌入、市场经济的深化以及互联网的萌芽几乎同步…...

Redis分布式锁进阶第一十一篇

一、本篇前置衔接 第一十一篇我们完成了全系列终局复盘,整理了故障排查SOP与企业级落地铁律。常规单资源锁、热点分片锁、隔离锁全部讲透,但真实复杂业务永远不是单一资源:下单要扣库存、扣优惠券、扣积分、冻结余额,多资源并行争…...

从文件上传到 RAG 检索:真正看懂了一个 AI 项目的知识库链路

一、前言:今天不是单独学一个知识点,而是串起了一条完整链路 今天继续分析 AI 项目中的 RAG 模块时,我发现自己之前对“文件上传”“文件切片”“向量化”“召回”“大模型回答”这些概念,虽然都单独听过,但真正放到项…...

2026年HR推荐的10个专业简历模板网站,从模板到写法

2026年HR推荐的10个专业简历模板网站,从模板到写法写一份让HR眼前一亮的简历,是很多求职者遇到的难题。模板选什么风格、内容怎么写才专业、怎么排版才不会被系统筛掉——这些问题常常让人头疼。这篇文章整理了10个HR推荐的专业简历模板网站,…...

CANN 算子调优:榨干昇腾硬件性能

一、算子性能分析基础 1.1 算子执行模型 昇腾上每个算子的执行都会经历:编译时优化 → 运行时调度 → 硬件执行。任何一个环节出问题都会导致性能下降。 ┌────────────────────────────────────────┐ │ 算子执…...

3个核心功能揭秘:JiYuTrainer如何让极域电子教室不再束缚你的学习自由

3个核心功能揭秘:JiYuTrainer如何让极域电子教室不再束缚你的学习自由 【免费下载链接】JiYuTrainer 极域电子教室防控制软件, StudenMain.exe 破解 项目地址: https://gitcode.com/gh_mirrors/ji/JiYuTrainer 你是否曾在学校机房被极域电子教室的全屏广播困…...

1987年7月14日晚上19-21点出生性格、运势和命运

1987年6月28日,距离二十四节气中的“小暑”(通常在7月6-8日)约8-10天。小暑意为“天气开始炎热但未到极致”,是盛夏的序曲。这个时节的哲学,与个人成长有着奇妙的呼应。性格的“小暑特质”:温润与韧性 小暑…...

如何10倍提升英语学习效率:词达人自动化助手终极教程

如何10倍提升英语学习效率:词达人自动化助手终极教程 【免费下载链接】cdr 微信词达人,高正确率,高效简洁。支持班级任务及自选任务 项目地址: https://gitcode.com/gh_mirrors/cd/cdr 核心关键词:词达人自动化助手、Pytho…...

PHP - PHP 简易 Web 服务器、基础接口开发

一、PHP 简易 Web 服务器 1、基本介绍 PHP 自带一个简易的 Web 服务器,适合快速测试,启动方式如下 php -S 【监听地址】:【监听端口】# 例如php -S 127.0.0.1:80002、注意事项 通过以下方式启动,就需要通过 localhost 访问,而不能…...

写给前端的 CANN-GraphCompiler:昇腾图编译器到底是啥?

写给前端的 CANN-GraphCompiler:昇腾图编译器到底是啥? 之前有兄弟问:“哥,PyTorch 模型怎么在昇腾上跑?中间有什么编译过程?” 好问题。今天一次说清楚。 GraphCompiler 是啥? GraphCompiler 是…...

ElevenLabs河南话合成效果翻车?5大本地化陷阱与97.3%可听度提升实测方案

更多请点击: https://codechina.net 第一章:ElevenLabs河南话语音合成效果翻车现象全景扫描 近期多位河南本地开发者及方言内容创作者反馈,ElevenLabs官方API在调用其“multilingual v2”模型尝试生成河南话(中原官话郑开片&…...

将数据从 OPPO 传输到 iPhone 的 4 个有效方案

拥有华丽的设计和强大的功能,谁不想拥有一部新的 iPhone?如果您是Android OPPO 用户,现在正准备换用新 iPhone,您可能会担心数据传输的问题。由于 OPPO 和 iPhone 的操作系统不同,很多人觉得将 OPPO 手机转换为 iPhone…...

ElevenLabs荷兰文语音生成速度对比实测:从4.2s→0.8s的WebSocket流式优化路径(附可复用代码片段)

更多请点击: https://intelliparadigm.com 第一章:ElevenLabs荷兰文语音生成速度对比实测:从4.2s→0.8s的WebSocket流式优化路径(附可复用代码片段) ElevenLabs 的 Dutch(nl-NL)语音合成在默认…...

野兽派不是乱来:拆解Midjourney V6中色彩暴力、笔触失序与构图反叛的5层参数逻辑

更多请点击: https://kaifayun.com 第一章:野兽派不是乱来:Midjourney V6的美学暴动宣言 Midjourney V6 不是一次平滑迭代,而是一场蓄谋已久的视觉政变——它将“语义精确性”与“风格不可预测性”焊死在同一张提示词底片上。当 …...

前端架构演进:从单体到微前端

前端架构演进:从单体到微前端 前端架构的发展历程 第一阶段:单体应用(Mono Repo) ├── src/ │ ├── components/ │ ├── pages/ │ ├── services/ │ ├── utils/ │ └── styles/ └── index.html…...

Github创建项目(创建仓库、新建项目、新建仓库)步骤

文章目录 新建项目然后根据指示创建第一个提交并推送即可 新建项目 然后根据指示创建第一个提交并推送即可 echo "# xxxxxxxx" >> README.md git init git add README.md git commit -m "first commit" git branch -M main git remote add origin ht…...

大模型终于看懂立体几何!中科院联合阿里提出统一形式语言,刷新解析SOTA

论文详细解读:使用统一形式化语言的平面与立体几何图形解析 论文标题:Geoparsing: Diagram Parsing for Plane and Solid Geometry with a Unified Formal Language作者机构:中国科学院自动化研究所(CASIA)、中国科学…...

Agentic Search能替代GraphRAG吗,结论清晰了

2024 年 GraphRAG 爆火以来,「要不要建图」成了 RAG 系统设计中最常被讨论的决策。建图能显著提升多跳推理性能,但代价高昂——实体抽取、图谱构建、索引维护,每一步都是真金白银。 与此同时,agentic search 系统快速崛起——Sear…...