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

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.欢迎交流讨论共同进步。
http://www.zskr.cn/news/1341733.html

相关文章:

  • 抖音获客失效?拆解本地商家流量困局的底层逻辑与破局路径
  • torchtitan-npu:大模型训练框架快速上手实战
  • 人工智能将如何创造就业:从岗位替代到生态重构的深度解析
  • 打通本地与云端,LangChain 混合部署环境的兼容性避坑手册
  • 【多通道滤波】基于最小均方(McFxLMS)算法用于自适应多通道有源噪声控制(MCANC)应用研究(Matlab代码实现)
  • ElevenLabs陕西话支持深度测评(含3大隐藏限制与绕过方案):实测87%方言词准确率背后的工程真相
  • 2026年HR推荐的10个专业简历模板网站,从模板到写法
  • BOM(全)
  • 谷歌收录怎么做比较快?Shopify过滤5个无效参数提升商品页收录
  • CANN 算子调优:榨干昇腾硬件性能
  • 谷歌收录排名怎么做比较好?靠这套内链策略15天提升50%流量
  • 2026黄冈白蚁消杀技术全解析:杭州白蚁消杀、柳州白蚁消杀、桂林白蚁消杀、梅州白蚁消杀、汕头白蚁消杀、温州白蚁消杀选择指南 - 优质品牌商家
  • 1987年6月27日下午13-15点出生性格、运势和命运
  • 3个核心功能揭秘:JiYuTrainer如何让极域电子教室不再束缚你的学习自由
  • 1987年7月14日晚上19-21点出生性格、运势和命运
  • 谷歌收录排名怎么做比较好?解决GSC已发现未编入的3个步骤
  • 微信聊天记录永久保存指南:5分钟掌握WeChatMsg完整备份方案
  • Github创建项目(创建仓库、新建项目、新建仓库)步骤
  • 大模型终于看懂立体几何!中科院联合阿里提出统一形式语言,刷新解析SOTA
  • 印地语语音合成落地难?ElevenLabs官方未披露的4大限制、3种绕过技巧,及2个替代模型性能对比数据
  • LLM 认知框架:揭秘时间序列与空间结构,洞悉 AI 未来!
  • UVa 12572 RMQ Overkill
  • 【编号884】江西省各城市-春节人口迁徙规模数据(2019-2025)
  • UVa 250 Pattern Matching Prelims
  • 嵌入式测试学习第 16 天:复位电路、电源电路基础原理
  • Python微服务架构:从单体到分布式的演进
  • UVa 253 Cube Painting
  • 5大优势解锁跨平台直播聚合:PureLive如何重塑你的直播观看体验
  • 2026年4月超纯水设备企业推荐,10吨双级高纯水设备/高纯水设备/超纯水设备/软化水设备,超纯水设备采购渠道怎么选择 - 品牌推荐师
  • 2026年山地车定制厂家综合:途锐达凭何成为口碑之选? - 2026年企业推荐榜