HTTP Methods
For a REST API, your service will want to support different verbs/methods. Http4s has a list of all the methods you’re familiar with, and a few more.
import fs2.Task
// import fs2.Task
import io.circe.generic._
// import io.circe.generic._
import io.circe.syntax._
// import io.circe.syntax._
import org.http4s._, org.http4s.dsl._
// import org.http4s._
// import org.http4s.dsl._
import org.http4s.circe._
// import org.http4s.circe._
@JsonCodec case class TweetWithId(id: Int, message: String)
// defined class TweetWithId
// defined object TweetWithId
@JsonCodec case class Tweet(message: String)
// defined class Tweet
// defined object Tweet
def getTweet(tweetId: Int): Task[Option[TweetWithId]] = ???
// getTweet: (tweetId: Int)fs2.Task[Option[TweetWithId]]
def addTweet(tweet: Tweet): Task[TweetWithId] = ???
// addTweet: (tweet: Tweet)fs2.Task[TweetWithId]
def updateTweet(id: Int, tweet: Tweet): Task[Option[TweetWithId]] = ???
// updateTweet: (id: Int, tweet: Tweet)fs2.Task[Option[TweetWithId]]
def deleteTweet(id: Int): Task[Unit] = ???
// deleteTweet: (id: Int)fs2.Task[Unit]
implicit val tweetWithIdEncoder = jsonEncoderOf[TweetWithId]
// tweetWithIdEncoder: org.http4s.EntityEncoder[TweetWithId] = org.http4s.EntityEncoder$$anon$2@2680d80a
implicit val tweetDecoder = jsonOf[Tweet]
// tweetDecoder: org.http4s.EntityDecoder[Tweet] = org.http4s.EntityDecoder$$anon$2@28211756
val tweetService = HttpService {
case GET -> Root / "tweets" / IntVar(tweetId) =>
getTweet(tweetId)
.flatMap(_.fold(NotFound())(Ok(_)))
case req @ POST -> Root / "tweets" =>
req.as[Tweet].flatMap(addTweet).flatMap(Ok(_))
case req @ PUT -> Root / "tweets" / IntVar(tweetId) =>
req.as[Tweet]
.flatMap(updateTweet(tweetId, _))
.flatMap(_.fold(NotFound())(Ok(_)))
case req @ HEAD -> Root / "tweets" / IntVar(tweetId) =>
getTweet(tweetId)
.flatMap(_.fold(NotFound())(_ => Ok()))
case req @ DELETE -> Root / "tweets" / IntVar(tweetId) =>
deleteTweet(tweetId)
.flatMap(_ => Ok())
}
// tweetService: org.http4s.HttpService = Kleisli(org.http4s.package$HttpService$$$Lambda$29494/1361633949@ac779c0)
There’s also DefaultHead
which replicates the functionality of the native
implementation of the HEAD
route.