FastAPI+React全栈开发04 FastAPI概述

发布于:2024-03-29 ⋅ 阅读:(21) ⋅ 点赞:(0)

Chapter01 Web Development and the FARM Stack

04 Introducing FastAPI

FastAPI+React全栈开发04 FastAPI概述

Now we will look at a brief introducion to the Python REST-API framework of choice - FastAPI. Additionally, we will go over a high-level overview of the features that make it a protagonist in our FARM stack. I will try to compare FastAPI with Python and JavaScript alternatives and explain why it can be a great fit for a modern and flexible stack.

现在我们将简要介绍所选择的Python REST-API框架—FastAPI。此外,我们将对使其成为FARM堆栈中的主角的特性进行高级概述。我将尝试比较FastAPI与Python和JavaScript的替代品,并解释为什么它可以非常适合现代和灵活的堆栈。

REST APIs

What is an API? Technically, API stands for Application Programming Interface. APIs are used to enable some kind of interaction between different pieces of software and different systems, and they communicate using HTTP (short for Hypertext Transfer Protocol) through a cycle of requests and responses. In the last couple of decades, APIs have become the standard protocol for communication between various servers and heterogeneous clients, and they can be seen as a sort of vascular system that is fundamental to information exchange on the web.

什么是API?从技术上讲,API代表应用程序编程接口。api用于支持不同软件和不同系统之间的某种交互,它们通过请求和响应的循环使用HTTP(超文本传输协议的缩写)进行通信。在过去的几十年里,api已经成为各种服务器和异构客户端之间通信的标准协议,它们可以被视为一种血管系统,是web上信息交换的基础。

There are many definitions, more or less formal ones, and application programming interfaces can mean many things, but I like to view them as wirings that expose the business logic through a uniform interface, allowing us to use them from another realm.

有许多定义,或多或少是正式的定义,应用程序编程接口可以意味着许多东西,但我喜欢将它们视为通过统一接口公开业务逻辑的连接,允许我们从另一个领域使用它们。

An API is, as its name suggests, an interface. It is a way for a human or a machine to interact with an application or a service through an interface. Every API provider will provide an interface that is well-suited for the type of data that they provide, for instance, a weather forecasting station will provide an API that lists the temperatures and humidity levels for a certain period and a certain location. Some sports sites will provide statistical data about the games that are being played and a pizza delivery API will provide you with the selected ingredients, the price, and the estimated time of arrival. APIs are everywhere, inside your TV, your wallet, and heck, your favorite news site probably uses at least a dozen of them. With the adoption of the Internet of Things, APIs will enter even more aspects of our lives, transmitting biometric and medical data, enabling fast communications between factory machines, tractors in the fields, traffic frequencies, traffic light control systems, and more. APIs are what makes today’s web turn, what generates traffic, and ultimately, what generates revenue. Put simply, we can think of an API as a standardized way of information exchange, with usability, performance, and scalability in mind.

顾名思义,API是一个接口。它是人或机器通过接口与应用程序或服务交互的一种方式。每个API提供者都将提供一个非常适合其提供的数据类型的接口,例如,天气预报站将提供一个API,列出特定时间段和特定位置的温度和湿度水平。一些体育网站将提供有关正在进行的比赛的统计数据,而比萨饼配送API将为您提供所选的配料、价格和预计到达时间。api无处不在,在你的电视里,在你的钱包里,见鬼,你最喜欢的新闻网站可能至少使用了一打api。随着物联网的采用,api将进入我们生活的更多方面,传输生物识别和医疗数据,实现工厂机器,田间拖拉机,交通频率,交通灯控制系统等之间的快速通信。api使今天的网络转向,产生流量,最终产生收益。简单地说,我们可以把API看作是一种标准化的信息交换方式,考虑到可用性、性能和可伸缩性。

We will not go over the rigorous definitions of REST APIs, but just list some of the most important ones:

  • Statelessness: REST APIs are said to be stateless, which means that neither the client nor the server stores any states in-between. All the requests and responses are handled by the PAI server in isolation and without information about the session itself.
  • Layered structure: In order to keep the API scalable and understandable, a RESTful architecture implies a layered structure. The different layers form a hierarchy and communicate with each other but not with every component, thus improving overall security.
  • Client-server architecture: APIs should be able to connect different systems/pieces of software without limiting their own functionalities, the server (the system that provides the response) and the client (the system making the request) have to stay separate and independent from each other.

我们不会详细介绍REST api的严格定义,只列出一些最重要的定义:

  • 无状态:REST api被认为是无状态的,这意味着客户端和服务器之间都不存储任何状态。所有请求和响应都由PAI服务器单独处理,不包含会话本身的信息。
  • 分层结构:为了保持API的可扩展性和可理解性,RESTful架构意味着分层结构。不同的层形成一个层次结构,彼此通信,但不是与每个组件通信,从而提高了整体安全性。
  • 客户端-服务器架构:api应该能够连接不同的系统/软件,而不限制它们自己的功能,服务器(提供响应的系统)和客户端(发出请求的系统)必须保持彼此分离和独立。

We will be using FastAPI for our REST API layer, and we could say that it checks all the required boxes and then some more.

我们将使用FastAPI作为REST API层,我们可以说它检查了所有必需的框,然后还有更多。

What is FastAPI?

FastAPI is a modern and performant web framework for building APIs. Built by Sebastian Ramirez, it uses, to best avail, the newest features of the Python programming language, such as type hinting and annotations, the async-await syntax, Pydantic models, web socket support, and more.

FastAPI是一个用于构建api的现代高性能web框架。它由Sebastian Ramirez构建,充分利用了Python编程语言的最新特性,例如类型提示和注释、async-await语法、Pydantic模型、web套接字支持等等。

There are numerous reasons why FastAPI, though relatively new, will probably see a wider spread in the web development world in the future, so let’s list some of them:

  • High performance: FastAPI is able to achieve very high performance, especially compared to other Python-based solutions. By using Starlette under the hood, FastAPI’s performance reaches levels that are usually reserved for Node.js and Go.
  • Data validation and simplicity: Being heavily based on Python types and Pydantic brings numerous benefits. Since Pydantic structures are just instances of classes the developers define, we can perform complex data validations, deeply nested JSON objects, and hierarchical models (using Python lists and dictionaries), and this relates very well with the nature of MongoDB.
  • Faster development: Development becomes more intuitive, with strong integrated development environment(IDE) support, which leads to faster development time and fewer bugs.
  • Standards compliance: FastAPI is standard based and fully compatible with open standards for building APIs - OpenAPI and JSON schemas.
  • Logical structuring of apps: The framework allows for structuring of APIs and apps into multiple reouters and allows granular request and response customization. and easy access to every part of the HTTP cycle.
  • Async support: FastAPI uses an Asynchrounous Server Gateway Interface (ASGI) and, with the use of an ASGI compatible server, such as Uvicorn or Hypercorn, is able to provide a truly asynchronous workflow without actually having to import the Async.io module into Python.
  • Dependency injection: The dependency injection system in FastAPI is one of its biggest selling points. It enables us to create complex functionalities that are easily reusable across our API. This is a pretty big deal and probably the feature that makes FastAPI ideal for hybrid web apps, it gives developers the opportunity to easily attach different functionalities to the REST endpoints.
  • Great documentation: The documentation of the framework itself is excellent and second to none. It is both easy to follow and extensive.
  • Automatic documentation: Being based on OpenAPI, FastAPI enables automatic documentation creation, which essentially means that we get our API documented for free with Swagger.

FastAPI虽然相对较新,但在未来的web开发领域可能会有更广泛的应用,这里有很多原因,所以让我们列出一些原因:

  • 高性能:FastAPI能够实现非常高的性能,特别是与其他基于python的解决方案相比。通过在底层使用Starlette, FastAPI的性能达到了通常为Node.js和Go保留的水平。
  • 数据验证和简单性:基于Python类型和Pydantic带来了许多好处。由于Pydantic结构只是开发人员定义的类的实例,因此我们可以执行复杂的数据验证,深度嵌套的JSON对象和分层模型(使用Python列表和字典),这与MongoDB的性质非常相关。
  • 更快的开发:开发变得更加直观,强大的集成开发环境(IDE)支持,这导致更快的开发时间和更少的错误。
  • 符合标准:FastAPI是基于标准的,完全兼容开放的标准,用于构建api - OpenAPI和JSON模式。
  • 应用程序的逻辑结构:该框架允许将api和应用程序结构成多个路由器,并允许粒度请求和响应定制。并且可以轻松访问HTTP周期的每个部分。
  • 异步支持:FastAPI使用异步服务器网关接口(ASGI),并使用ASGI兼容服务器,如Uvicorn或Hypercorn,能够提供真正的异步工作流,而无需实际导入Async.io模块导入Python。
  • 依赖注入:依赖注入系统是FastAPI最大的卖点之一。它使我们能够创建复杂的功能,这些功能很容易在我们的API中重用。这是一个非常重要的功能,可能是使FastAPI成为混合web应用程序的理想特性,它使开发人员有机会轻松地将不同的功能附加到REST端点。
  • 出色的文档:框架本身的文档非常出色,首屈一指。它既容易遵循又广泛。
  • 自动文档:基于OpenAPI, FastAPI支持自动文档创建,这本质上意味着我们可以使用Swagger免费获取API文档。

In order to get at least a basic idea of what coding with FastAPI looks like, let’s take a look at a miniamal API:

为了至少对FastAPI的编码有一个基本的概念,让我们来看一个最小的API:

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"Message": "Hello World"}

The preceding few lines of code define a minimal API with a single endpoint(/) that responds to a GET request with the message “Hello world”. We instantiate a FastAPI class and use decorators to tell the server which HTTP methods should trigger which function for a response, just like with the Flask microframework, for example.

前面的几行代码定义了一个带有单个端点(/)的最小API,它用消息“Hello world”响应GET请求。我们实例化一个FastAPI类,并使用装饰器告诉服务器哪个HTTP方法应该触发哪个函数来响应,就像Flask微框架一样。

Python and REST APIs

Python has been used to build REST APIs for a very long time. While there are many options and solutions, DRF and Flask seem to be the most popular ones, at least until recently. If you are feeling adventurous, you can Google less popular or older frameworks such as bottle.py and CherryPy. DRF is a plug-in system for the Django web framework and enables a Django system to create highly customized REST API responses and generate endpoints based on the defined models. DRF is a very mature and battle tested system. It is regularly updated, and its documentation is very detailed. Flask, Python’s lightweight microframework, is a real gem among the web-building Python tools and can create REST APIs in a lot of different ways. You can use pure Flask and just output the appropriate format (i.e., JSON instead of HTML) or use some of the extensions developed to make the creation of REST APIs as straightforward as possible. Both of these solutions are fundamentally sysnchronous, although there seems to be active development in the direction of enabling async support.

Python用于构建REST api已经有很长时间了。虽然有许多选择和解决方案,但DRF和Flask似乎是最受欢迎的,至少直到最近。如果您喜欢冒险,您可以Google不太流行或较老的框架,如bottle.py和CherryPy。DRF是Django web框架的一个插件系统,它使Django系统能够创建高度自定义的REST API响应,并根据定义的模型生成端点。DRF是一个非常成熟和经过实战测试的系统。它定期更新,其文档非常详细。Flask, Python的轻量级微框架,是构建web的Python工具中的一个真正的宝石,可以用很多不同的方式创建REST api。你可以使用纯Flask,只输出适当的格式(例如,JSON而不是HTML),或者使用一些开发的扩展,使REST api的创建尽可能简单。这两种解决方案基本上都是同步的,尽管似乎正在朝着启用异步支持的方向积极发展。

There are also some very robust and mature tools, such as Tonado, which is an asynchronous networking library(and a server) that is able to scale to tens of thousands of open connections. Finally, in the last couple of years, several new Python based solutions have been created.

还有一些非常健壮和成熟的工具,例如Tonado,它是一个异步网络库(和服务器),能够扩展到数万个打开的连接。最后,在过去几年中,已经创建了几个新的基于Python的解决方案。

One of these solutions, and arguably the fastest, is Starlette. Dubbed as a lightweight ASGI framework/toolkit, it is ideal for building high-performance async services.

其中一个解决方案,可以说是最快的,是Starlette。它被称为轻量级的ASGI框架/工具包,是构建高性能异步服务的理想选择。

Like Flask was built on top of a couple of solid Python libraries, Werkzeug and Jinja2, 10 or more years ago, Sebastian Ramirez built FastAPI on top of Starlette and Pydantic, while also adding numerous features and goodies by using the latest Python features, such as type hinting and async support. According to some recent surveys, FastAPI is quickly becomming one of the most popular and most loved web frameworks. Undeniably, it is gaining in popularity, and it looks like it is here to stay, at least for the foreseeble future.

就像10多年前Flask是在几个坚实的Python库Werkzeug和Jinja2上构建的一样,Sebastian Ramirez在Starlette和Pydantic上构建了FastAPI,同时通过使用最新的Python特性(如类型提示和异步支持)添加了许多功能和优点。根据最近的一些调查,FastAPI正迅速成为最流行和最受喜爱的web框架之一。不可否认的是,它越来越受欢迎,看起来至少在可预见的未来,它将继续存在。

In Chapter 3, Getting Started with FastAPI, of this book, we will go over the most important features of FastAPI, but at this point, I just want to stress the significance of having a truly async Python framework as the glue for the most diverse components of a system. In fact, besides doing the usual web framework stuff, such as communicating with a database or, in our case, a MongoDB store, spitting out data to a frontend, and managing authentication and authorization, this Python pipeline enables us to quickly integrate and easily achieve frequently required tasks such as background jobs, header and body manipulation, response and request validation, and more through the dependency injection system.

在本书的第3章,FastAPI入门中,我们将讨论FastAPI最重要的特性,但在这一点上,我只想强调拥有一个真正的异步Python框架作为系统中最多样化组件的粘合剂的重要性。事实上,除了做通常的web框架的事情,比如与数据库通信,或者在我们的例子中,与MongoDB存储通信,向前端输出数据,以及管理身份验证和授权,这个Python管道使我们能够快速集成并轻松实现经常需要的任务,如后台作业,头部和正文操作,响应和请求验证,以及更多通过依赖注入系统。

We will try to cover the absolute minimum necessary for you to be able to build a simple FastAPI system. I will make frequent trips to the official documentation site and try to find the simplest solutions. Lastly, we will consider various web server solutions and deployment options(such as Deta, Heroku, and Digitalocean) for our FastAPI Python-based backend, while trying to opt for free solutions.

我们将尝试涵盖您能够构建一个简单的FastAPI系统所需的绝对最低限度。我将经常访问官方文档站点,并尝试找到最简单的解决方案。最后,我们将为FastAPI基于python的后端考虑各种web服务器解决方案和部署选项(如Deta、Heroku和Digitalocean),同时尝试选择免费的解决方案。

So, to cut a long story short, we choose FastAPI because we ideally want the ability and speed to handle requests asynchronously as if we were using a Node.js server while having access to the Python ecosystem. Additionally, we want the simplicity and development speed of a framework that automatically generates documentation for us.

所以,长话短说,我们选择FastAPI,是因为我们理想地想要异步处理请求的能力和速度,就像我们使用Node.js服务器一样,同时可以访问Python生态系统。此外,我们希望框架的简单性和开发速度能够自动为我们生成文档。

After reviewing the backend components, it is time to finalize our stack and put a face on it. We will now look at a minimal introduction to React and discuss what distinguishes it from other(also valid) solutions.

在检查了后端组件之后,是时候完成我们的堆栈并对其进行处理了。现在,我们将简单介绍一下React,并讨论它与其他(同样有效的)解决方案的区别。

本文含有隐藏内容,请 开通VIP 后查看