Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple REST API calls using Spring?

Okay I'm having a simple REST API that is now running. I also got a mobile app (Android) that would be ready for some network communication. But here is the thing:

I now got a fancy API created with Spring that I can use with Http-Requests:

package com.helloworld

@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(ModelMap model) {
        model.addAttribute("msg", "JCG Hello World!");
        return "helloWorld";
    }
}

This is all fine but how would I use this API in my Android mobile App? What I mean is that I don't know how to make those calls more elegantly and simple! I don't want to write for every request on my API something like this:

class HelloWorldTask extends AsyncTask<String, String, String> {

    private String url = "http://192.168.42.229:8080/HelloWorldExample/helloWorld/displayMessage/" + msg; 

    @Override
    protected String doInBackground(String... uri) {

        String msg = "";
        for(String m : uri) { msg += m; }    

        RestTemplate restTemplate = new RestTemplate();    
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        return restTemplate.getForObject(url, String.class, "Android");
    }
}

Is there any way to avoid this? To be honest I believed that I would be able to just import something like a helloworld-api.jar after building my REST API project and then do something like this:

import com.helloworld

public void getServerHello() {

    HelloWorldController api;

    HelloWorld helloWorld = api.getHelloWorldMapping();
    helloWorld.displayMessage("How are you?");
}

And that this will be it. So is there a way to do something like this when writing a Spring REST API or will I really have to use something like a URI-builder and create for all kind of requests an additional class <whatever>Task extends AsyncTask<?, ?, ?> by myself?

Since the API is clearly defined it should be possible to do something like this, but is it?

I hope my question is clear - please let me know if not.

like image 842
Stefan Falk Avatar asked Jul 03 '26 00:07

Stefan Falk


1 Answers

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.itech.payroll.dto.ComypanyDTO;
import com.itech.payroll.dto.EmployeeDTO;
import com.itech.payroll.dto.User;
import com.itech.payroll.repo.PayrollRepo;
import com.itech.payroll.service.PayrollService;
import com.itech.payroll.service.UserService;
/**
 * REST API Implementation Using REST Controller
 * */
@RestController
public class RestReqCntrl {

    @Autowired
    private UserService userService;    

    @Autowired
    private PayrollService payrollService;  


    //-------------------Create a User--------------------------------------------------------

    @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
    public ResponseEntity<User> registerUser(@RequestBody User user,    UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating User " + user.getFirstName());

        boolean flag = userService.registerUser(user);

         if (flag)
         {
             user.setStatusCode(1);
             user.setStatusDesc("PASS");
         }else{
             user.setStatusCode(0);
             user.setStatusDesc("FAIL");

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerUser").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<User>(user,headers, HttpStatus.CREATED);
    }   

    //-------------------Authenticating the User--------------------------------------------------------

    @RequestMapping(value = "/authuser", method = RequestMethod.POST)
    public ResponseEntity<User> authuser(@RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating User " + user.getFirstName());

        boolean flag = userService.authUser(user);

         if (flag)
         {
             user.setStatusCode(1);
             user.setStatusDesc("PASS");
         }else{
             user.setStatusCode(0);
             user.setStatusDesc("FAIL");

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
        return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
    }   

    //-------------------Create a Company--------------------------------------------------------
    @RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
    public ResponseEntity<String> registerCompany(@RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
        String result ="";
        boolean flag = payrollService.registerCompany(comypanyDTO);

         if (flag)
         {
             result="Pass";
         }else{
             result="Fail";

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
        return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
    }   


    //-------------------Create a Employee--------------------------------------------------------
    @RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
    public ResponseEntity<String> registerEmployee(@RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
        String result ="";
        boolean flag = payrollService.registerEmpbyComp(employeeDTO);

         if (flag)
         {
             result="Pass";
         }else{
             result="Fail";

         }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
        return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
    }   

    //-------------------Get Company Deatils--------------------------------------------------------
    @RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
    public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
        System.out.println("getCompanies getCompanies ");
        List<ComypanyDTO> comypanyDTOs =null;
        comypanyDTOs = payrollService.getCompanies();
        //Setting the Respective Employees
        for(ComypanyDTO dto :comypanyDTOs){

            dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
        return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
    }   

}
like image 152
Raj Sharma Avatar answered Jul 05 '26 14:07

Raj Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!