# Return different type of response based on Accept header

I'm a novice to Scala and Akka-Http and am experimenting with Akka-Http for writing rest services. I have to return JSON or protobuf based on the Accept-Header.

optionalHeaderValueByName("Accept"){ contentType =>
if(contentType == Some(protoEncode)) {
complete {
NewsService.getNewsList().map {
case stories: List[Story] =>    HttpResponse(entity = HttpEntity(ContentType(protoEncoding),  StoryList(stories).toProto().build().toByteArray))
}
}
} else {
complete {
NewsService.getNewsList().map {
case stories: List[Story] => StoryList(stories)
}
}
}


As you can see, the code repetition is happening. Can anyone suggest what could be the best way to optimise and generalise the design to avoid such a situation?

• Hi and welcome to Code Review. In order to avoid confusion for future readers and invalidating existing answers, if you have found improvements on your own, please post them as an answer. If you have updated your code and would like the (new) code reviewed, please post a follow-up question.
– Kaz
Dec 11 '15 at 9:42
• Welcome to Code Review! I have rolled back the last edit. Please see what you may and may not do after receiving answers. Dec 11 '15 at 9:43

I don't know Akka-Http API well enough, but it looks like the if condition is misplaced. I think that it can be substituted with a matcher under case stories:

optionalHeaderValueByName("Accept") { contentType =>
complete {
NewsService.getNewsList().map {
case stories: List[Story] => {
contentType match {
case Some(protoEncode) =>
HttpResponse(entity = HttpEntity(ContentType(protoEncoding), StoryList(stories).toProto().build().toByteArray))
case None => StoryList(stories)
}
}
}
}
}


It seems that it is a bit too deeply nested, but at least there is no repetition on NewsService.getNewsList().map.

• Thanks for the answer. the way you suggested would work generally. But, akka-http complete method doesn't accept two different return types. I've updated the code please check it out. Dec 11 '15 at 9:22