Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Thursday, April 2, 2020

Spring REST Controller: Resolve conflicts between root controllers endpoints and swagger-ui.html


Our team had some issues setting up swagger. We've been adding swagger to multiple services and for a strange reason, one service was not loading the swagger-ui.html. After some testing, we realize there was a conflict with some endpoint that were mapping to the root of the site:

@RestController
public class ReportController {
    
    @RequestMapping(method = RequestMethod.GET, value = "/{reportId}")
    public ResponseEntity getReport(@PathVariable String reportId) {
        ....
    }
}

As we can see, since controller class has no request mapping, and endpoint method is mapping with /{some_id}, when we try to hit /swagger-ui.html, the request is mapped to this method.

After googling a lot, we ended up just making our request mapping more specific to a certain type of ids. In our case we are using mongo ids for the reports. It means ids can only have number or letters in lowercase.


@RestController
public class ReportController {
    
    @RequestMapping(method = RequestMethod.GET, value = "/{reportId:^[0-9a-f]+$}")
    public ResponseEntity getReport(@PathVariable String reportId) {
        ....
    }
}

Now because swagger-ui.html contains a dot (.) and a dash (-), the request is not being caught by this endpoint anymore.

Monday, June 2, 2014

HalBuilder: First steps

My team and I are working on trying to find best Java client to consume Hal REST services. I was trying HalBuilder and took me a time to figure a few tweaks to make the simple example describe in the website to work. Perhaps, I was doing something wrong, but just in case someone is also stuck on that, here's the code:

Maven Dependencies:

<dependency>
 <groupId>com.theoryinpractise</groupId>
 <artifactId>halbuilder-api</artifactId>
 <version>2.2.1</version>
</dependency>
<dependency>
 <groupId>com.theoryinpractise</groupId>
 <artifactId>halbuilder-core</artifactId>
 <version>3.1.3</version>
</dependency>
<dependency>
 <groupId>com.theoryinpractise</groupId>
 <artifactId>halbuilder-json</artifactId>
 <version>3.1.3</version>
</dependency>
<dependency>
 <groupId>com.theoryinpractise</groupId>
 <artifactId>halbuilder-standard</artifactId>
 <version>3.0.1</version>
</dependency>

<dependency>
  <groupId>com.ning</groupId>
  <artifactId>async-http-client</artifactId>
  <version>1.8.9</version>
</dependency>

Java code:

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import com.theoryinpractise.halbuilder.api.ReadableRepresentation;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
import com.theoryinpractise.halbuilder.json.JsonRepresentationFactory;

//http://gotohal.net/
public class TestHalBuilderAPI {
 
 public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
  RepresentationFactory representationFactory = new JsonRepresentationFactory();
  representationFactory.withFlag(RepresentationFactory.PRETTY_PRINT);  
  
  AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
  Response response = asyncHttpClient.prepareGet("http://gotohal.net/restbucks/api").execute().get();
  
  InputStreamReader inputStreamReader = new InputStreamReader(response.getResponseBodyAsStream());
 
  ReadableRepresentation representation = representationFactory.readRepresentation(inputStreamReader);
  String ordersLinkUrl = representation.getLinkByRel("orders").getHref();  
  System.out.println(ordersLinkUrl);  
  asyncHttpClient.close();
 }
}

Wednesday, May 1, 2013

Spring Jackson library example to consume JSON returned by REST service


A brief example of how to use the Spring Jackson library to consume a JSON returned by a REST service. The class below is a Singleton that initializes the RestTemple one time only.

import java.util.ArrayList;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.http.client.CommonsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class RestJsonTest {
 
 private static RestJsonTest instance;
 private RestTemplate restTemplate;
 private String url ="http://rest.service.url";
 
 public static RestJsonTest getInstance() {
  if (instance == null) {
   instance = new RestJsonTest();
  }
  return instance;
 }
 
 private RestJsonTest() {
  // Setup the RestTemplate configuration.
  restTemplate = new RestTemplate();
  restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory());
  List<HttpMessageConverter<?>> messageConverterList = restTemplate.getMessageConverters();
  
  // Set HTTP Message converter using a JSON implementation.
  MappingJacksonHttpMessageConverter jsonMessageConverter = new MappingJacksonHttpMessageConverter();
  
  // Add supported media type returned by BI API.
  List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
  supportedMediaTypes.add(new MediaType("text", "plain"));
  supportedMediaTypes.add(new MediaType("application", "json"));
  jsonMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
  messageConverterList.add(jsonMessageConverter);
  restTemplate.setMessageConverters(messageConverterList);
 }
 
 public SearchResults searchResults() {
  return restTemplate.getForObject(url, SearchResults.class);  
 }
 
 public static void main(String[] args) {
  RestJsonTest jsonTest = RestJsonTest.getInstance();
  SearchResults results = jsonTest.searchResults();
 }
}

The mapping of the JSON to Java classes can be done via annotations like it's shown here:
package com.bodybuilding.api.commerce.clientservice;

import java.util.List;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;


/**
 *{
 * "search_keywords":"Social Networks",
 *  "total_time":200,
 *  "results":{
 *   "result_01":{
 *    "url":"http://www.facebook.com",
 *    "rank": "1"
 *   },
 *   "result_02":{
 *   "url":"http://www.twitter.com",
 *    "rank": "2"
 *   }
 *  }
 * }
 */
@JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResults {
 
 @JsonProperty("search_keywords")
 private String keywords;
 
 @JsonProperty("total_time")
 private long totalTime;
 
 @JsonProperty("results")
 private List<SearchResult> results;
 
 public String getKeywords() {
  return keywords;
 }
 public void setKeywords(String keywords) {
  this.keywords = keywords;
 }
 public long getTotalTime() {
  return totalTime;
 }
 public void setTotalTime(long totalTime) {
  this.totalTime = totalTime;
 }
 public List<SearchResult> getResults() {
  return results;
 }
 public void setResults(List<SearchResult> results) {
  this.results = results;
 } 
}

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResult {
 
 @JsonProperty("url")
 private String url;
 
 @JsonProperty("rank")
 private int rank;
 
 public String getUrl() {
  return url;
 }
 public void setUrl(String url) {
  this.url = url;
 }
 public int getRank() {
  return rank;
 }
 public void setRank(int rank) {
  this.rank = rank;
 }
}

The RestTemplate bean can be also configure with Spring injection:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
     <property name="requestFactory">
      <bean id="clientHttpRequestFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory" />   
     </property>
     <property name="messageConverters">
      <list>
       <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
         <list>
          <bean id="jsonMediaTypeTextPlain" class="org.springframework.http.MediaType">
           <constructor-arg value="text"/>
          <constructor-arg value="plain"/>
          </bean>
          <bean id="jsonMediaTypeApplicationJson" class="org.springframework.http.MediaType">
           <constructor-arg value="application"/>
          <constructor-arg value="json"/>
          </bean>
         </list>
        </property>
       </bean>
      </list>
     </property>  
</bean>