首页  >  文章  >  后端开发  >  使用 Python 快速创建 API

使用 Python 快速创建 API

Barbara Streisand
Barbara Streisand原创
2024-10-23 20:07:02746浏览

“使用 FastAPI 在 5 分钟内创建 API。FastAPI 是一个现代的高性能 Python 框架,可以轻松构建强大的 Web 应用程序。”

安装
使用 pip 安装 FastAPI 和 uvicorn(ASGI 服务器):

pip install fastapi uvicorn
pip install fastapi

让我们创建我们的 API

打开记事本并粘贴以下内容,将文件另存为data.json(我们将使用POST方法向该文件添加数据,并使用GET方法检索记录

data.json

[
   {
      "name": "John",
      "age": 25
   },
   {  "name": "Smith",
      "age": 27
   }
]

现在创建一个新的 python 文件,将其命名为 app.py 并粘贴以下代码

# This section imports necessary modules and classes from the FastAPI library and Python's standard library. It imports FastAPI for creating the web application, HTTPException for raising HTTP exceptions, List for type hints, and json for working with JSON data.

from fastapi import FastAPI, HTTPException
from typing import List
import json

# This creates an instance of the FastAPI class, which will be the main application instance for handling HTTP requests.
app = FastAPI()

# This block reads the content of the "data.json" file using a context manager (with statement) and loads the JSON data into the initial_data variable.
with open("data.json", "r") as file:
    initial_data = json.load(file)

# This line initializes the data variable with the loaded JSON data, effectively creating a list of dictionaries containing user information.
data = initial_data

# This decorator (@app.get(...)) defines a GET endpoint at the "/users" URL. It uses the get_users function to handle the request. The response_model parameter specifies the expected response model, which is a list of dictionaries in this case.
@app.get("/users", response_model=List[dict])
async def get_users():
    return data

# This decorator (@app.post(...)) defines a POST endpoint at the "/users" URL. It uses the create_user function to handle the request. The response_model parameter specifies the expected response model, which is a single dictionary in this case.
# The create_user function attempts to append the received user dictionary to the data list. If successful, it constructs a response dictionary indicating the success. If an exception occurs during the attempt (e.g., due to invalid data), it constructs a response dictionary indicating an error.
@app.post("/users", response_model=dict)
async def create_user(user: dict):
    try:
        data.append(user)
        response_data = {"message": "User created successfully", "user": user}
    except:
        response_data = {"message": "Error creating user", "user": user}
    return response_data

# This function uses a context manager to open the "data.json" file in write mode and then uses json.dump to write the contents of the data list back to the file, formatting it with an indentation of 4 spaces.
def save_data():
    with open("data.json", "w") as file:
        json.dump(data, file, indent=4)

# This decorator (@app.on_event(...)) defines a function that will be executed when the FastAPI application is shutting down. In this case, it calls the save_data function to save the data back to the JSON file before the application exits.
@app.on_event("shutdown")
async def shutdown_event():
    save_data()

# This block checks if the script is being run directly (not imported as a module). If it is, it uses the uvicorn.run function to start the FastAPI application on host "0.0.0.0" and port 8000. This is how you launch the application using the Uvicorn ASGI server.
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

运行app.py,Uvicorn服务器将启动一个新进程来处理传入的HTTP请求。服务器启动并运行后,打开 Postman,使用 URL 创建一个新的 GET 请求:http://0.0.0.0:8000/users,然后单击发送

Create API’s in inutes with Python

Create API’s in inutes with Python

您将看到一个 JSON 响应,其中包含 data.json 文件中的用户列表。

现在让我们使用 POST 方法将用户添加到该文件中。创建一个新请求,选择 POST 方法,单击正文,选择原始,从下拉列表中选择 JSON 并将以下 JSON 粘贴为有效负载以添加新用户

{
    "name": "Tina",
    "age": 22
}

Create API’s in inutes with Python

点击发送后,如果用户添加成功,您将收到回复,状态码为 200 OK

Create API’s in inutes with Python

就是这样,我们已经成功创建了一个具有 GET/POST 方法的 API 来查看用户并将用户添加到文件中。返回 GET 请求并单击发送,您现在应该看到用户 Tina 也列在 API 的响应中。

FastAPI 的一个令人惊奇的事情是它会自动为您的 API 端点生成 Swagger 文档,使开发人员更容易有效地理解和使用您的 API。

如果您打开浏览器并输入 http://localhost:8000/docs,您将看到 API 的 swagger 文档

Create API’s in inutes with Python

请注意,这只是使用 python 创建快速 API 的基本示例,您还需要进行更多配置或编码,特别是在错误处理、数据验证和安全性方面。

以上是使用 Python 快速创建 API的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn