DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Micronaut Mastery: Return Responses Based on the HTTP Accept Header

Micronaut Mastery: Return Responses Based on the HTTP Accept Header

Take a look at how to get your Micronaut-based microservice to format its response based on a request's Accept header.

Hubert Klein Ikkink user avatar by
Hubert Klein Ikkink
·
Aug. 24, 18 · Tutorial
Like (2)
Save
Tweet
Share
13.87K Views

Join the DZone community and get the full member experience.

Join For Free

Suppose we want our controller methods to return a JSON response when the HTTP Accept header is set to application/json and XML when the Accept header is set to application/xml. We can access the values of HTTP headers in our controller methods by adding an argument of type HttpHeaders to our method definition and Micronaut will add all HTTP headers with their values as HttpHeaders object when we run the application. In our method, we can check the value of the Accept header and return a different value based on the header value.

In the following example controller, we have a sample method with an argument of the type HttpHeaders. We check the value of the Accept header using the method accept and return either XML or JSON as the response.

package mrhaki.micronaut;

import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

@Controller("/message")
public class MessageController {

    @Get("/")
    public HttpResponse<?> sample(final HttpHeaders headers) {
        // Simple object to be returned from this method either
        // as XML or JSON, based on the HTTP Accept header.
        final Message message = new Message("Micronaut is awesome");

        // Check if HTTP Accept header is "application/xml".
        if (headerAcceptXml(headers)) {
            // Encode messages as XML.
            final String xml = encodeAsXml(message);

            // Return response and set content type 
            // to "application/xml".
            return HttpResponse.ok(xml)
                               .contentType(MediaType.APPLICATION_XML_TYPE);
        }

        // Default response as JSON.
        return HttpResponse.ok(message);
    }

    /**
     * Check HTTP Accept header with value "application/xml"
     * is sent by the client.
     * 
     * @param headers Http headers sent by the client.
     * @return True if the Accept header contains "application/xml".
     */
    private boolean headerAcceptXml(final HttpHeaders headers) {
        return headers.accept().contains(MediaType.APPLICATION_XML_TYPE);
    }

    /**
     * Very simple way to create XML String with message content.
     * 
     * @param message Message to be encoded as XML String.
     * @return XML String with message content.
     */
    private String encodeAsXml(final Message message) {
        return String.format("<content>%s</content>", message.getContent());
    }

}

The Message class that is converted to XML or JSON is simple:

package mrhaki.micronaut;

public class Message {

    final String content;

    public Message(final String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

}

When we run the application and GET /message with the HTTP Accept header value application/xml, we get the following response:

<content>Micronaut is awesome</content>

And with the HTTP Accept header value application/json, we get the following response:

{
    "content": "Micronaut is awesome"
}

We can test our controller with the following Spock specification:

package mrhaki.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.MediaType
import io.micronaut.http.client.RxHttpClient
import io.micronaut.runtime.server.EmbeddedServer
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class MessageControllerSpec extends Specification {

    @Shared
    @AutoCleanup
    private static EmbeddedServer embeddedServer =
            ApplicationContext.run(EmbeddedServer)

    @Shared
    @AutoCleanup
    private static RxHttpClient client =
            embeddedServer.applicationContext
                          .createBean(RxHttpClient, embeddedServer.getURL())

    void "get message as XML"() {
        given:
        final request = HttpRequest.GET("/message").accept(MediaType.APPLICATION_XML_TYPE)
        HttpResponse response = client.toBlocking().exchange(request, String)

        expect:
        response.status == HttpStatus.OK
        response.body() == 'Micronaut is awesome' } void "get message as JSON"() { given: HttpResponse response = client.toBlocking().exchange("/message", Message) expect: response.status == HttpStatus.OK response.body().getContent() == 'Micronaut is awesome' } }

Written with Micronaut 1.0.0.M4.

application XML JSON Spock (testing framework) Testing Object (computer science)

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • How To Handle Secrets in Docker
  • 10 Best Ways to Level Up as a Developer
  • Unlocking the Power of Elasticsearch: A Comprehensive Guide to Complex Search Use Cases

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: