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

使用sttp/tapir测试带JSON体的Endpoint时遇404/400错误求助

问题排查与修复

一、派生Input返回404的核心原因

你定义的端点路径是accounts/{id}/test-request,但测试请求用的是uri"http://test.com/test-request",完全缺失accounts/{id}前缀和id路径参数。Tapir的Stub会严格匹配请求路径的每一部分,路径不匹配直接返回404,这是最直接的问题。

二、手动jsonBody返回400的原因

400错误提示请求体无效,结合你的场景,大概率是两个问题:

  • 缺少必填Header:你的端点要求Source-Event-Timestamp和Accept两个Header,但测试请求里只设置了contentType,未传递这两个头。Stub会校验所有定义的输入参数,缺失会导致请求不符合端点要求,触发参数解析错误。
  • 编解码器配置问题:如果LocalDateTime没有正确配置zio-json编解码器,或者Payload的编解码器未正确导入,会导致请求体或Header解析失败。

修复后的代码示例

修正端点定义(确保编解码器可用)

先确认导入tapir与zio-json的集成包,并给LocalDateTime添加编解码器:

import tapir._
import tapir.generic.auto._
import tapir.json.zio._
import zio.json._
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

// 给LocalDateTime添加zio-json编解码器
implicit val localDateTimeCodec: JsonCodec[LocalDateTime] = JsonCodec.string.transform(
  LocalDateTime.parse(_, DateTimeFormatter.ISO_LOCAL_DATE_TIME),
  _.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
)

case class Payload(one: String, two: String)
object Payload {
  implicit val codec: JsonCodec[Payload] = DeriveJsonCodec.gen[Payload]
}

@endpointInput("accounts/{id}/test-request")
final case class RequestInput(
    @path id: String,
    @header("Source-Event-Timestamp") sourceEventTimestamp: LocalDateTime,
    @header("Accept") accept: String,
    @jsonbody payload: Payload
)

val baseEndpoint = endpoint.errorOut(stringBody)
val input = EndpointInput.derived[RequestInput]
val endpoint = baseEndpoint.post.in(input).out(stringBody)

修正测试代码

补上完整路径、路径参数和必填Header,确保请求与端点定义完全匹配:

import sttp.client3._
import sttp.tapir.client.sttp.TapirStubInterpreter
import zio._
import zio.test._

test("带JSON体的端点测试") {
  for {
    stub <- ZIO.succeed {
      TapirStubInterpreter(SttpBackendStub(new RIOMonadAsyncError[Any]))
        .whenServerEndpoint(endpoint)
        .thenRunLogic((_: RequestInput) => ZIO.succeed("success"))
        .backend()
    }
    body = """{"one": "test", "two": "test"}"""
    response <- basicRequest
      .contentType("application/json")
      .header("Source-Event-Timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
      .header("Accept", "application/json")
      .body(body)
      .post(uri"http://test.com/accounts/123/test-request") // 补上完整路径和id参数
      .send(stub)
  } yield assertTrue(response.code == StatusCode.Ok, response.body == Right("success"))
}

额外注意点

Tapir的Stub对请求的匹配是全参数严格校验,路径、Header、请求体、查询参数等所有定义的输入都必须完全匹配,否则会返回404或400。实际服务器运行正常是因为你实际请求中传递了所有必填参数,只是测试用例遗漏了。

内容的提问来源于stack exchange,提问作者Bender Rodriguez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:02:47