Django API中通过GET方法发送JSON数据但后端无法接收
Django API GET请求无法接收JSON数据的问题解决
问题概述
使用requests.get(url, json={"query":"Hello"})发送GET请求时,Django后端的request.body为空,无法获取到发送的JSON数据。
相关代码及输出
客户端代码(client.py)
import requests endpoint = "http://127.0.0.1:8000/api" response = requests.get(endpoint, json={"query":"Hello"}) print(response.text) print(response.json()['Message']) print(response.status_code)
后端视图代码(views.py)
import json from django.http import JsonResponse def api_home(request, *args, **kwargs): body = request.body print(body) # 输出为空字节串b'' print("Request Received.....") print("Responding.....") return JsonResponse({"Message" : "Hi there, this is your django api response"})
客户端终端输出
{"Message": "Hi there, this is your django api response"} Hi there, this is your django api response 200
服务端输出
b'' Request Received..... Responding.....
问题原因
requests.get()方法的json参数不会将JSON数据放入请求体——因为HTTP规范中GET请求通常不携带请求体,大部分服务器(包括Django)会直接忽略GET请求的请求体内容。实际上,当你在GET请求中使用json参数时,requests会自动将JSON数据转换为URL查询参数,而非放在请求体内。
解决方案
方案1:改用POST请求(推荐)
如果需要传递JSON数据,遵循HTTP规范改用POST请求是更合理的选择:
修改后的客户端代码
import requests endpoint = "http://127.0.0.1:8000/api" # 改用post方法,json参数会被放入请求体 response = requests.post(endpoint, json={"query":"Hello"}) print(response.text) print(response.json()['Message']) print(response.status_code)
修改后的后端视图代码
import json from django.http import JsonResponse def api_home(request, *args, **kwargs): body = {} if request.method == "POST": # 解析请求体中的JSON数据 try: body = json.loads(request.body) print(body) # 输出{'query': 'Hello'} except json.JSONDecodeError: pass print("Request Received.....") print("Responding.....") return JsonResponse({ "Message" : "Hi there, this is your django api response", "received_data": body })
方案2:继续使用GET请求,通过查询参数传递数据
如果必须使用GET请求,需将数据作为查询参数传递,后端从request.GET中获取:
修改后的客户端代码
import requests endpoint = "http://127.0.0.1:8000/api" # 使用params参数传递查询参数,替代json参数 response = requests.get(endpoint, params={"query":"Hello"}) print(response.text) print(response.json()['Message']) print(response.status_code)
修改后的后端视图代码
from django.http import JsonResponse def api_home(request, *args, **kwargs): # 从request.GET中获取查询参数 query_data = request.GET.get("query") print(f"Received query: {query_data}") # 输出Received query: Hello print("Request Received.....") print("Responding.....") return JsonResponse({ "Message" : "Hi there, this is your django api response", "received_query": query_data })
内容的提问来源于stack exchange,提问作者Sahil Garg
相关产品推荐
相关产品推荐

