title: Calling REST API from MVC Controller (Spring MVC)
body: <p>EDIT --</p>
  <p>This is a stupid question - please ignore it. Going away to learn Java properly.</p>
  <p>--</p>
  <p>I want to create an API that can be used externally, but I also want to create my own front end to the same API.</p>
  <p>If I create an MVC controller &amp; a REST controller in the same app, can I call the REST API from the MVC controller without making an &quot;external&quot; http call, which seems a bit wasteful?</p>
  <p>(EDIT - originally linked to another question but it ws wrong. Can't find the right one so removed).</p>
  <p>Obviously raises the further question of whether I should or not, but that is, I suppose, subjective. As an aside I'd welcome opinion on that.</p>
  <p>EDIT 2 (to add some code in response to chrylis)</p>
  <p>So if I create a class like this (example copied from a tutorial somewhere)</p>
  <pre><code>public class Greeting {
      private final long id;
      private final String content;
  
      public Greeting(long id, String content) {
          this.id = id;
          this.content = content;
      }
  
      public long getId() {
          return id;
      }
  
      public String getContent() {
          return content;
      }   
  }
  </code></pre>
  <p>and a rest controller like this which if called directly from the browser will return json data :</p>
  <pre><code>@RestController
  public class GreetingController {
  
      private static final String template = &quot;Hello, %s!&quot;;
      private final AtomicLong counter = new AtomicLong();
  
      @RequestMapping(&quot;/greeting&quot;)
      public Greeting greeting(@RequestParam(value=&quot;name&quot;, required=false, defaultValue=&quot;World&quot;) String name) {
          return new Greeting(counter.incrementAndGet(),
                              String.format(template, name));
      }
      
  }
  </code></pre>
  <p>Then I call it from my HTML controller like this :</p>
  <pre><code>@Controller
  public class HomeController {
  
      private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
      
      @RequestMapping(&quot;/&quot;)
      public String home(Model model) {
          
          Greeting gr=new Greeting(1,&quot;Hi&quot;);
          logger.info(gr.getContent());
          
          model.addAttribute(&quot;modelName&quot;,gr.getContent());
          return &quot;home&quot;;
      }
  }
  </code></pre>
  <p>is that what you mean? It seems to work. The only issue I see is that I'm working on the class directly and not performing the action of the rest api.</p>
  <p>Actually, even as I write this I realise this isn't what you meant, I don't think.</p>