FastAPI+React全栈开发14 FastAPI如何开发REST接口

Chapter03 Getting Started with FastAPI

14 How does FastAPI speak REST

FastAPI+React全栈开发14 FastAPI如何开发REST接口

Let's create a minial FastAPI application, a classic Hello World example, and start examining how FastAPI structures the endpoints. I use the term endpoint to specify a unique combination of an URL (which will always be the same, in our case, our development server, that is, localhost:8000), a path (the part after the slash), and an HTTP method. In a new folder named Chapter 3, for example, create a new Python file using Visual Studio Code.

让我们创建一个小型的FastAPI应用程序,一个经典的Hello World示例,并开始研究FastAPI如何构建端点。我使用术语端点来指定URL(始终是相同的,在我们的示例中,是我们的开发服务器,即localhost:8000)、路径(斜杠后面的部分)和HTTP方法的唯一组合。例如,在名为Chapter 3的新文件夹中,使用Visual Studio Code创建一个新的Python文件。

python 复制代码
from fastapi import FastAPI

app = FastAPI()


@app.get('/')
async def root():
    return {"message": "Hello FastAPI"}

In just a few lines of code, we were able to accomplish serveral things. So, let's break down what each part does.

在短短的几行代码中,我们完成了几件事。那么,让我们分解一下每个部分的作用。

In the first line of main.py, we imported the FastAPI class from the fastapi package. Then, we instantiated an application object (we called it app since that is considered a good practice, but we could have chosen any name). This is just a Python class that provides all the functionality of our API and exposes an ASGI compatible application, this is the application that we have to pass to our server of choice (Uvicorn).

在main.py的第一行,我们从FastAPI包中导入了FastAPI类。然后,我们实例化一个应用程序对象(我们将其称为app,因为这被认为是一种良好的做法,但我们可以选择任何名称)。这只是一个Python类,它提供了我们API的所有功能,并公开了一个ASGI兼容的应用程序,这是我们必须传递给我们选择的服务器(Uvicorn)的应用程序。

The application is now ready and instantiated, but without endpoints, it isn't able to do or say very much. FastAPI, similar to Flask, another popular Python web framework, exposes decorators for HTTP methods to enable the application to respond. However, we have to implement them.

应用程序现在已经准备好并实例化了,但是没有端点,它就不能做很多事情或说很多话。FastAPI,类似于Flask(另一个流行的Python web框架),为HTTP方法公开装饰器,使应用程序能够响应。然而,我们必须实现它们。

After that, we used the @get decorator, which corresponds to the GET method, and we passed a URL, in our case, we used /, which is the root path.

之后,我们使用了@get装饰器,它对应于GET方法,我们传递了一个URL,在我们的例子中,我们使用了/,这是根路径。

The decorated function is called root, another convention, but it could be called what ever we wanted (any valid Python function name). It is responsible for accepting any arguments (in our case, there aren't any) and responding. The value that's returned by the function, which in our case is a simple Python dictionary, will then be transformed into a JSON response and returned by the ASGI server as an HTTP response. This may seem obvious, but I believe that it is useful to break things down into the tiniest bits in the beginning.

修饰函数被称为root,这是另一种约定,但它可以被称为我们想要的任何名称(任何有效的Python函数名)。它负责接受任何参数(在我们的例子中,没有任何参数)并做出响应。函数返回的值(在我们的示例中是一个简单的Python字典)将被转换为JSON响应,并由ASGI服务器作为HTTP响应返回。这似乎是显而易见的,但我相信在开始时将事情分解成最小的部分是有用的。

The preceding code defines a basic fully functional application with a single endpoint. To be able to test it, we need a server, enter Uvicorn.

前面的代码定义了一个具有单个端点的基本全功能应用程序。为了能够测试它,我们需要一个服务器,输入Uvicorn。

Now, go ahead and run the live server with Uvicorn in your command line:

现在,在命令行中使用Uvicorn运行实时服务器:

bash 复制代码
uvicorn main:app --reload

The previous line is something that you will be using quite a lot when developing with FastAPI, so let's break ti down.

在使用FastAPI进行开发时,您将经常使用前面的代码行,因此让我们对其进行分解。

This is the out put that you will get if you test our only endpoint with HTTPie (note that when we omit the kyword, it defaults to GET):

如果你用HTTPie测试我们唯一的端点,你会得到这样的输出(注意,当我们省略关键字时,它默认为get):

bash 复制代码
http localhost:8000

If we wanted to create an endpoint that responds with the same message but for POST requests, we would just have a change the decorator:

如果我们想创建一个端点,用相同的消息响应,但对于POST请求,我们只需要改变装饰器:

python 复制代码
from fastapi import FastAPI

app = FastAPI()


@app.post('/')
async def root():
    return {"message": "Hello FastAPI"}


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app)

HTTPie will respond accordingly in the terminal:

HTTPie将在终端中做出相应的响应:

bash 复制代码
http POST localhost:8000
相关推荐
轻口味4 分钟前
【每日学点鸿蒙知识】AVCodec、SmartPerf工具、web组件加载、监听键盘的显示隐藏、Asset Store Kit
前端·华为·harmonyos
alikami7 分钟前
【若依】用 post 请求传 json 格式的数据下载文件
前端·javascript·json
wakangda38 分钟前
React Native 集成原生Android功能
javascript·react native·react.js
吃杠碰小鸡41 分钟前
lodash常用函数
前端·javascript
emoji1111111 小时前
前端对页面数据进行缓存
开发语言·前端·javascript
泰伦闲鱼1 小时前
nestjs:GET REQUEST 缓存问题
服务器·前端·缓存·node.js·nestjs
m0_748250031 小时前
Web 第一次作业 初探html 使用VSCode工具开发
前端·html
一个处女座的程序猿O(∩_∩)O1 小时前
vue3 如何使用 mounted
前端·javascript·vue.js
m0_748235951 小时前
web复习(三)
前端
AiFlutter1 小时前
Flutter-底部分享弹窗(showModalBottomSheet)
java·前端·flutter