0Pricing
Scala for Backend Engineering & Functional Programming · 课时

JSON 端点

将 http4s 与 Circe 结合起来。

JSON 端点 是 CoddyKit 上的免费 Scala for Backend Engineering & Functional Programming 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Scala for Backend Engineering & Functional Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

JSON via circe

http4s integrates JSON through the http4s-circe module, which bridges circe codecs to EntityDecoder and EntityEncoder. circe is the de facto functional JSON library for Scala.

You define Encoder and Decoder instances for your types and let http4s handle the wire format.

// build.sbt
// "org.http4s" %% "http4s-circe" % http4sV
// "io.circe"   %% "circe-generic" % circeV

Deriving Codecs

With circe-generic you derive codecs automatically using deriveEncoder/deriveDecoder or the @JsonCodec annotation. They map case-class fields to JSON keys by name.

Derivation needs codecs for every field type, recursively.

import io.circe.generic.semiauto._

case class User(id: Int, name: String)
implicit val enc = deriveEncoder[User]
implicit val dec = deriveDecoder[User]

EntityEncoder from circe

The import org.http4s.circe.CirceEntityEncoder._ provides an implicit EntityEncoder[F, A] for any A with a circe Encoder. Then Ok(user) serializes to JSON with application/json.

No manual conversion to Json is needed in handlers.

import org.http4s.circe.CirceEntityEncoder._

HttpRoutes.of[IO] {
  case GET -> Root / "me" => Ok(User(1, "Ada"))
}

EntityDecoder from circe

Mirror image: org.http4s.circe.CirceEntityDecoder._ supplies an EntityDecoder[F, A] for any A with a circe Decoder. Then req.as[User] parses the JSON body.

Both imports together are bundled as CirceEntityCodec._.

import org.http4s.circe.CirceEntityDecoder._

case req @ POST -> Root / "users" =>
  req.as[User].flatMap(u => Created(u))

A Full JSON POST

Combining decode and encode gives a clean create endpoint: parse the incoming JSON to a domain type, run business logic, then encode the result back as JSON.

Decoding failures surface as 422 or 400 via the circe decoder.

import org.http4s.circe.CirceEntityCodec._

case req @ POST -> Root / "users" =>
  for {
    in  <- req.as[User]
    out <- store.create(in)
    res <- Created(out)
  } yield res

The json Interpolator

For ad hoc JSON, circe's json string interpolator from io.circe.literal builds a Json value directly, with interpolated Scala values.

Useful for small responses or test fixtures without a case class.

import io.circe.literal._

val body = json"""{ "status": "ok", "count": 3 }"""
Ok(body)

Custom Field Names

When JSON keys differ from Scala field names, derive with a Configuration from circe-generic-extras, e.g. snake_case, or write the codec by hand using forProduct2.

This decouples your API contract from internal naming.

import io.circe.Encoder

implicit val e: Encoder[User] =
  Encoder.forProduct2("user_id", "full_name")(u => (u.id, u.name))

Encoding Lists

circe provides codecs for List, Vector, Option, and Map automatically once the element codec exists. So returning a collection just works.

An empty list encodes to [] and None to either an absent key or null.

import org.http4s.circe.CirceEntityEncoder._

case GET -> Root / "users" =>
  store.all.flatMap(us => Ok(us)) // List[User] -> JSON array

Validating Decoded JSON

Decoding gives you a syntactically valid value; semantic validation is yours. Run checks after as and short-circuit with BadRequest when invalid.

Keep domain invariants in smart constructors returning Either for clarity.

req.as[User].flatMap { u =>
  if (u.name.nonEmpty) Created(u)
  else BadRequest("name required")
}

Error Responses as JSON

Return structured errors as JSON so clients can parse them. Define an error case class with a circe encoder and pass it to the relevant status builder.

Consistent error shapes make APIs far easier to consume.

case class ApiError(code: String, message: String)
implicit val e = deriveEncoder[ApiError]

BadRequest(ApiError("E_NAME", "name required"))

Streaming JSON

For large collections you can stream JSON instead of buffering. jsonEncoderOf plus an fs2 Stream[F, A] emits a JSON array incrementally.

This keeps memory flat for big result sets, leveraging fs2 back-pressure.

import org.http4s.circe.streamJsonArrayEncoder

case GET -> Root / "feed" =>
  Ok(store.streamAll) // fs2.Stream[IO, Event]

Quick Check

Recall which import enables decoding a JSON body to a case class.

Recap

You wired JSON with http4s-circe: derive codecs, import CirceEntityCodec, and use Ok(value) / req.as[A] for full JSON I/O.

You handled lists, custom field names, structured JSON errors, and even streaming arrays for large payloads.

常见问题解答

「JSON 端点」课时是免费的吗?

是的 — 「JSON 端点」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Scala for Backend Engineering & Functional Programming 课程的其余内容,请升级到 CoddyKit PRO。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。

「JSON 端点」这节课中我会学到什么?

将 http4s 与 Circe 结合起来。 你通过在浏览器中直接运行的动手代码来练习 Scala for Backend Engineering & Functional Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Scala for Backend Engineering & Functional Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Scala for Backend Engineering & Functional Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「JSON 端点」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Scala for Backend Engineering & Functional Programming 课中编写并运行代码吗?

能。每节 Scala for Backend Engineering & Functional Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 路由与 HttpRoutes
  2. 请求与响应
  3. JSON 端点
  4. 提供应用服务
← 返回 Scala for Backend Engineering & Functional Programming