wp_remote_post调用FastAPI接口报422错误的排查与解决
FastAPI接口在WordPress插件中wp_remote_post调用失败的解决方法
问题场景
本地服务器同时部署FastAPI接口与WordPress插件,接口通过Swagger UI、Python requests库调用均正常,但在WordPress插件中使用wp_remote_post调用时返回422错误。
FastAPI接口代码
from fastapi import FastAPI from pydantic import BaseModel from api.article import add_article, html_format_data app = FastAPI() class PostData(BaseModel): links: list title: str @app.post('/create_post/') def create_post(post_data: PostData): html_format = html_format_data(post_data.links, post_data.title) # list of dicts if add_article(post_data.title, html_format): return {"status": 201, "success": True} else: return {"error"}
正常工作的Python请求代码
import requests data = { "title": "gaming", "links": [ { "id": "video id 1", "thumbnail": "url of thumbnail 1", "title": "title of video 1" }, { "id": "video id 2", "thumbnail": "url of thumbnail 2", "title": "title of video 2" } ] } res = requests.post('http://127.0.0.1:5000/create_post/', json=data) print(res.content)
Swagger UI生成的curl调用示例
curl -X 'POST' \ 'http://127.0.0.1:5000/create_post/' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "links": [ { "id": "shortand", "thumbnail": "shortand", "title": "shortand" }, { "id": "shortand", "thumbnail": "shortand", "title": "shortand" } ], "title": "gaming" }'
WordPress插件中错误的调用代码
function create_post( $data, $query ) { $url = 'http://127.0.0.1:5000/create_post/'; $arguments = array( 'method' => 'POST', 'body' => json_encode(array( "links" => $data, "title" => $query )), 'header' => array( 'Content-Type' => 'application/json', 'accept' => 'application/json' ) ); $response = wp_remote_post( $url, $arguments ); // echo '<script>console.log(`data: ' . $arguments["body"] . '`)</script>'; echo '<script>console.log(`' . json_encode($response) . '`)</script>'; }
报错信息
{"headers":{},"body":"{\"detail\":[{\"loc\":[\"body\"],\"msg\":\"value is not a valid dict\",\"type\":\"type_error.dict\"}]}","response":{"code":422,"message":"Unprocessable Entity"},"cookies":[],"filename":null,"http_response":{"data":null,"headers":null,"status":null}}
解决过程与修正方案
排查后发现核心问题是wp_remote_post的参数拼写错误:将请求头参数的复数形式headers误写为单数header。这导致FastAPI无法识别请求的Content-Type,进而无法正确解析JSON格式的请求体,返回422验证错误。
修正后的WordPress调用代码:
function create_post( $data, $query ) { $url = 'http://127.0.0.1:5000/create_post/'; $arguments = array( 'method' => 'POST', 'body' => json_encode(array( "links" => $data, "title" => $query )), 'headers' => array( // 修正为复数形式headers 'Content-Type' => 'application/json', 'accept' => 'application/json' ) ); $response = wp_remote_post( $url, $arguments ); // echo '<script>console.log(`data: ' . $arguments["body"] . '`)</script>'; echo '<script>console.log(`' . json_encode($response) . '`)</script>'; }
内容的提问来源于stack exchange,提问作者SAVEPALASTINE
相关产品推荐
相关产品推荐

