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
相关推荐
Summer不秃3 分钟前
Flutter之使用mqtt进行连接和信息传输的使用案例
前端·flutter
旭日猎鹰8 分钟前
Flutter踩坑记录(二)-- GestureDetector+Expanded点击无效果
前端·javascript·flutter
Viktor_Ye14 分钟前
高效集成易快报与金蝶应付单的方案
java·前端·数据库
hummhumm16 分钟前
第 25 章 - Golang 项目结构
java·开发语言·前端·后端·python·elasticsearch·golang
乐闻x43 分钟前
Vue.js 性能优化指南:掌握 keep-alive 的使用技巧
前端·vue.js·性能优化
一条晒干的咸魚1 小时前
【Web前端】创建我的第一个 Web 表单
服务器·前端·javascript·json·对象·表单
Amd7941 小时前
Nuxt.js 应用中的 webpack:compiled 事件钩子
前端·webpack·开发·编译·nuxt.js·事件·钩子
生椰拿铁You1 小时前
09 —— Webpack搭建开发环境
前端·webpack·node.js
狸克先生1 小时前
如何用AI写小说(二):Gradio 超简单的网页前端交互
前端·人工智能·chatgpt·交互
baiduopenmap2 小时前
百度世界2024精选公开课:基于地图智能体的导航出行AI应用创新实践
前端·人工智能·百度地图