Home > Article > Backend Development > How to parse incoming JSON data using request body in FastAPI
How to parse incoming JSON data using the request body in FastAPI
FastAPI is a modern web framework based on Python that provides rich functionality and high-performance asynchronous support. When using FastAPI to handle HTTP requests, it is often necessary to parse the incoming JSON data. This article will introduce how to use the request body to parse incoming JSON data in FastAPI and provide corresponding code examples.
First, we need to import FastAPI dependencies and the JSONResponse module for processing and returning JSON data.
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse
Next, we create a FastAPI application object.
app = FastAPI()
Then, we write a routing processing functionparse_json
to process the received POST request and parse it Incoming JSON data.
@app.post("/parse_json") async def parse_json(request: Request): try: json_data = await request.json() # 在这里可以对json_data进行处理 return {"status": "success", "data": json_data} except Exception as e: return JSONResponse(status_code=400, content={"status": "error", "message": str(e)})
In the above code, we use the request.json()
method to parse the incoming JSON data. The parsed data will be stored in the json_data
variable in the form of a Python dictionary, which we can process further.
Finally, we start the FastAPI application.
if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)
So far, we have completed writing the code to use the request body to parse the incoming JSON data in FastAPI.
Usage example:
You can call ## by sending a POST request to http://localhost:8000/parse_json
and including JSON data in the request body. #parse_jsonRoute processing function and perform JSON data parsing.
$ curl -X POST -H "Content-Type: application/json" -d '{"name":"John", "age":30}' http://localhost:8000/parse_jsonThe return result is as follows:
{"status": "success", "data": {"name": "John", "age": 30}}If the incoming data is not in legal JSON format, a 400 error and corresponding errors will be returned Information:
{"status": "error", "message": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"}Summary: This article describes how to use the request body to parse incoming JSON data in FastAPI and provides corresponding code examples. Through the above steps, we can easily process the received JSON data and perform further operations and processing. I hope this article can help you parse JSON data in FastAPI development!
The above is the detailed content of How to parse incoming JSON data using request body in FastAPI. For more information, please follow other related articles on the PHP Chinese website!