FastAPI向量嵌入接口Laravel Guzzle请求报422,Curl/Postman正常
问题描述
我基于Universal Sentence Encoder模型搭建了一个FastAPI向量嵌入服务,用Postman或Curl发起请求时能正常工作,但通过Laravel的Guzzle发送表单POST请求时,会返回422 Unprocessable Entity错误。
相关代码及日志
1. FastAPI的schema.py代码
from pydantic import BaseModel class TextRequest(BaseModel): text: str
2. Laravel中Guzzle请求代码
use Illuminate\Support\Facades\Http; $response = Http::post('http://your-fastapi-service-url/embed', [ 'text' => '需要嵌入的文本内容' ]); dd($response->status(), $response->json());
3. Uvicorn错误日志
INFO: 192.168.1.100:54321 - "POST /embed HTTP/1.1" 422 Unprocessable Entity {"detail":[{"loc":["body","text"],"msg":"field required","type":"value_error.missing"}]}
4. 正常请求截图
- Postman请求成功截图:Postman成功界面
- Curl请求成功截图:Curl成功界面
问题原因
FastAPI默认要求请求体为application/json格式,而Guzzle默认发送的是application/x-www-form-urlencoded格式的表单数据,导致FastAPI无法识别请求体中的text字段,触发字段缺失的422错误。
解决方案
修改Laravel的Guzzle请求,强制发送JSON格式的请求体:
方法1:使用withJson()快捷方法
use Illuminate\Support\Facades\Http; $response = Http::withJson([ 'text' => '需要嵌入的文本内容' ])->post('http://your-fastapi-service-url/embed'); dd($response->status(), $response->json());
方法2:手动设置请求头并传递JSON字符串
use Illuminate\Support\Facades\Http; $response = Http::withHeaders([ 'Content-Type' => 'application/json', ])->post('http://your-fastapi-service-url/embed', json_encode([ 'text' => '需要嵌入的文本内容' ])); dd($response->status(), $response->json());
验证
修改后重新发起请求,FastAPI即可正确解析请求体中的text字段,返回正常的向量嵌入结果。
内容的提问来源于stack exchange,提问作者Jean Linux
相关产品推荐
相关产品推荐

