You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中ixdra/curl调用Stability AI API JSON格式错误修复求助

修复Stability AI文本转图像接口的JSON格式错误

问题场景

用户提供的Bash Curl代码可正常调用Stability AI的text-to-image接口,但在Laravel中使用ixdra/curl包编写的调用代码返回错误:

{"id":"dba28c896eb85a892b376b3f87bff0e7","message":"can't decode JSON request body: malformed JSON","name":"bad_request"}

错误原因

核心问题是text_prompts字段的结构不符合接口要求:

  • Bash示例中text_prompts是包含单个对象的数组:[{"text": "A lighthouse on a cliff"}]
  • 原Laravel代码中text_prompts直接是单个对象,缺少外层包裹的数组,导致生成的JSON格式错误。

修正后的代码

方法1:使用withJson方法(推荐)

ixdra/curl的withJson方法会自动处理JSON编码并设置正确的Content-Type:

$response = Curl::to('https://api.stability.ai/v1/generation/stable-diffusion-v1-5/text-to-image')
    ->withHeader('Authorization: Bearer sk-4TbivezpfB32bHGzaIbPd5S0NIzHQsN141kZ4FW0H31TrnLr')
    ->withJson([
        "text_prompts" => [
            ["text" => $prompts]
        ],
        "cfg_scale" => 7,
        "clip_guidance_preset" => 'FAST_BLUE',
        "height" => 512,
        "width" => 512,
        "samples" => 1,
        "steps" => 30
    ])
    ->post();

方法2:手动编码JSON并设置Content-Type

如果需要手动控制JSON编码,可使用json_encode配合withData:

$response = Curl::to('https://api.stability.ai/v1/generation/stable-diffusion-v1-5/text-to-image')
    ->withContentType('application/json')
    ->withHeader('Authorization: Bearer sk-4TbivezpfB32bHGzaIbPd5S0NIzHQsN141kZ4FW0H31TrnLr')
    ->withData(json_encode([
        "text_prompts" => [
            ["text" => $prompts]
        ],
        "cfg_scale" => 7,
        "clip_guidance_preset" => 'FAST_BLUE',
        "height" => 512,
        "width" => 512,
        "samples" => 1,
        "steps" => 30
    ]))
    ->post();

关键修正点

将原代码中的:

"text_prompts" => array( "text" => $prompts )

修改为:

"text_prompts" => array( array( "text" => $prompts ) )

(或短数组语法:"text_prompts" => [["text" => $prompts]])

内容的提问来源于stack exchange,提问作者Hirak Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:55:27