2

I have a Post request sent over a network to get data related to a user I'm using Http4s for this.

When writing the HttpRoutes I'm using this to handle the case of POST as follows:

case req @ POST -> Root/ "posts" { "name": username, "friends": friends} =>

the name and the friends are attributes passed as parameters in the body of the request.

Yet there is some syntax error I can seem to identify '=>' expected but '{' found.

Abhinav Gupta
  • 435
  • 1
  • 4
  • 13
A M
  • 23
  • 6

1 Answers1

7

That's an incorrect Scala syntax. Here's an example from the official http4s docs:

 case req @ POST -> Root / "hello" / id =>
    for {
      // Decode a User request
      user <- req.as[User]
      // Encode a hello response
      resp <- Ok(Hello(user.name).asJson)
    } yield (resp)

You're accessing API at "/hello" route. Then the request is decoded (unmarshalled) to User instance. E.g. you can use Circe JSON library to decode a content from a request:

import io.circe.generic.auto._
import io.circe.syntax._

import org.http4s._
import org.http4s.circe._

id is a path variable. Here, you can take a look how to use query params too: https://http4s.org/v0.21/dsl.

Circe encoder is being used to convert User instance to JSON content for the response.

Ok(Hello(user.name).asJson)
Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85