Niro
Niro

Reputation: 443

Akka http add header to POST request with body

I have an akka http route that accepts a json in the body of the request. I am trying to test that route by using akka http test kit.

val header = RawHeader("Content-Type", "application/json")
Post("/tasks", trigger.asJson.noSpaces) ~> addHeader(header) ~>
    addCredentials(OAuth2BearerToken(VALID_TOKEN)) ~> Route.seal(route) ~> check {
    status shouldBe StatusCodes.OK
  }

This test is failing with message

415 Unsupported Media Type was not equal to 200 OK 

How do i properly add the content type header to the request?

Upvotes: 1

Views: 2178

Answers (1)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

Let akka-http create RequestEntity on its own instead of passing json as String yourself.

You just need to pass trigger as the second parameter of Post.apply as is.

Post("/tasks", trigger) ~> addCredentials(OAuth2BearerToken(VALID_TOKEN)) ~> Route.seal(route) ~> check {
  status shouldBe StatusCodes.OK
}

This will require a ToEntityMarshaller[Trigger] available in your implicit context.

And you can add it in the same way as you do in you route definition by importing/extending de.heikoseeberger.akkahttpargonaut.ArgonautSupport and argonaut CodecJson[Trigger] if you use argonaut for example.

In case you want to pass arbitrary string value, do

Post("/tasks").withEntity(ContentTypes.`application/json`, someJsonAsString) ~> addCredentials(OAuth2BearerToken(VALID_TOKEN)) ~> Route.seal(route) ~> check {
   status shouldBe StatusCodes.OK
}

Upvotes: 1

Related Questions