title: How to Consume REST Api and then Display Top Stories as JSON
body: <p><strong>GOAL:</strong> Create a Spring Boot Project to consume a public API for NY Times to display the Top Stories at the moment.</p>
  
  <p><strong>What I have done:</strong> I have consumed the REST Api and stored my response into a jsonObject. I have trying the pass the two unit tests, but unable to pass the first junit test. Pretty sure what I am doing is incorrect even though I am passing the second junit test.</p>
  
  <p><strong>News POJO</strong></p>
  
  <pre><code>public class News {
  
  private String title;
  private String section;
  
  // GETTER &amp; SETTER
  
  }
  </code></pre>
  
  <p><strong>News Service Class</strong></p>
  
  <pre><code>@Service public class NewsService {
  
  private String apiKey = "gIIWu7P82GBslJAd0MUSbKMrOaqHjWOo";
  
  public News getTopStories() throws Exception {
  
  
      RestTemplate restTemplate = new RestTemplate();
      News news = new News();
  
      String getUrl = "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=" + apiKey;
  
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON);
  
      HttpEntity&lt;String&gt; entity = new HttpEntity&lt;String&gt;(headers);
      ResponseEntity&lt;Map&gt; newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
      JSONObject jsonObject;
  
      if (newsList.getStatusCode() == HttpStatus.OK) {
  
          jsonObject = new JSONObject(newsList.getBody());
          JSONArray jsonArray = jsonObject.getJSONArray("results");
  
          for(int i=0; i&lt;jsonArray.length(); i++) {
  
              news.setTitle(jsonArray.getJSONObject(i).get("title").toString());
              news.setSection(jsonArray.getJSONObject(i).get("section").toString());
  
          }
      }
      // this is only returning the last index of the jsonArray (pretty sure I am suppose to return all to in my URL). Can't seem to come up with the logic to do that.
      return news; 
  }
  
  }
  </code></pre>
  
  <p><strong>News Controller Class</strong></p>
  
  <pre><code>import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
  import org.springframework.web.bind.annotation.RestController;
  
  @RestController
  @RequestMapping("/api")
  public class NewsController {
  
  @Autowired
  NewsService newsService;
  
  @RequestMapping(value = "/news/topstories", method = RequestMethod.GET)
  public News getNews() throws Exception {
      return newsService.getTopStories();
  }
  
  }
  </code></pre>
  
  <p><strong>JUnit Test Needing to Pass</strong></p>
  
  <pre><code>@Test
  public void retrievetest_ok() throws Exception {
  
       mockMvc.perform(get("/api/news/topstories" )).andDo(print())
                  .andExpect(status().isOk())
                  .andExpect(MockMvcResultMatchers.jsonPath("$.results.[0].title").exists())
                  .andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());
  
  
  }
  
  @Test public void Newstest_ok() throws Exception {
      mockMvc.perform(get("/api/news/topstories" ))
              .andDo(print())
              .andExpect(status().isOk())
              .andExpect(MockMvcResultMatchers.jsonPath("$.title").exists())
              .andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());
  }
  
  
  }
  </code></pre>
  
  <p><strong>Error I receive for first JUnit Test</strong></p>
  
  <pre><code>MockHttpServletRequest:
    HTTP Method = GET
    Request URI = /api/news/topstories
     Parameters = {}
        Headers = {}
  
  Handler:
           Type = com.example.project.NewsController
         Method = public com.example.project.News com.example.project.NewsController.getNews() throws java.lang.Exception
  
  Async:
    Async started = false
    Async result = null
  
  Resolved Exception:
           Type = null
  
  ModelAndView:
      View name = null
           View = null
          Model = null
  
  FlashMap:
     Attributes = null
  
  
   MockHttpServletResponse:
         Status = 200
   Error message = null
        Headers = {Content-Type=[application/json;charset=UTF-8]}
   Content type = application/json;charset=UTF-8
           Body = {"title":"Shrinking and Quaking Hint at Moon’s Tectonic Life","section":"Science"}
  Forwarded URL = null
  Redirected URL = null
        Cookies = []
  
  java.lang.AssertionError: No value at JSON path "$.results.[0].title", exception: Missing property in path $['results']
  ...
  ...
  ...
  ...
  </code></pre>