How to create and call API in Grail

By | June 5th 2019 01:09:04 PM | viewed 161 times

How to create Restfull Api in grails:

Step1

in application.yml => add the following code:

grails:
  profile: web
  cors:
    enabled: true

add the plugins in the location: build.gradle =>

dependencies {
    compile 'org.grails.plugins:grails3-cors-interceptor:1.2.1'
}
Step2

Create a controller as follows:

package com.allClass.lps.tesco

import com.allClass.accs.AccsCustomerSnno
import com.allClass.auth.User
import grails.converters.JSON
import org.springframework.security.access.annotation.Secured
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.CrossOrigin

@Transactional(readOnly = true)
@Secured(['permitAll'])
class TransitStickerApiController {

    def index() { }

    def uktoken(){
	
        if (request.method == 'GET') {
            return "anf254874365_#98541265"
        } else {
            return "method not allowed"
        }

    }
	
    def customerInfoById() {

        def getToken
        def getInfo

        if(request.method == 'GET'){

                getToken = this.uktoken()

                if(getToken == "anf254874365_#98541265"){

                    if(params?.get("id")){
                        getInfo = this.getCustomerInfoById(params?.get("id"))
                        render (getInfo as JSON)
                    }else{
                        render(["Message":"id parameter not found"] as JSON)
                    }


                }else{
                    render(["Message":"token invalid"] as JSON)
                }

            }else{
                render(["Message":"method not alloed"] as JSON)
            }
    }


    def getCustomerInfoById(def idnumber) {

        Map setMaster = new HashMap()
        List accsCustomerSnno
        User userInstance

        userInstance  = User?.findById(Long.parseLong(idnumber?.toString()))

        if(userInstance){
            if(userInstance?.customerId?.id){
                accsCustomerSnno  = AccsCustomerSnno?.findAllByAccsCustomer(userInstance?.customerId)
            }
            setMaster.put("user_id",userInstance?.id)
            setMaster.put("user_username",userInstance?.username)
            setMaster.put("user_password",userInstance?.password)
            setMaster.put("user_fullName",userInstance?.fullName)
            setMaster.put("user_cellNo",userInstance?.cellNo)
            setMaster.put("user_email",userInstance?.email)
            setMaster.put("user_employeeId",userInstance?.employeeId)
            setMaster.put("user_type_id",userInstance?.userType?.id)
            setMaster.put("user_type_name",userInstance?.userType?.keyword)
            setMaster.put("user_country",userInstance?.countryName)
            setMaster.put("user_created",userInstance?.created)

            setMaster.put("customer_id",userInstance?.customerId?.id)
            setMaster.put("customer_name",userInstance?.customerId?.customerName)
            setMaster.put("customer_eqos_code",userInstance?.customerId?.eqosCode)
            setMaster.put("customer_type",userInstance?.customerId?.customerType)
            setMaster.put("customer_group",userInstance?.customerId?.accsCustGrOfCom?.groupName)
            setMaster.put("customer_phone_no",userInstance?.customerId?.phoneNo)
            setMaster.put("customer_factory_one",userInstance?.customerId?.addressFactOne)
            setMaster.put("customer_factory_two",userInstance?.customerId?.addressFactTwo)
            setMaster.put("customer_factory_three",userInstance?.customerId?.addressFactThree)
            setMaster.put("customer_category",userInstance?.customerId?.customerCategory)


            setMaster.put("customer_contact_person_id",userInstance?.accsCustContPerson?.contPersonName)
            setMaster.put("customer_contact_person_name",userInstance?.accsCustContPerson?.contPersonName)
            setMaster.put("customer_contact_person_type",userInstance?.accsCustContPerson?.contPersonType)
            setMaster.put("customer_contact_person_designation",userInstance?.accsCustContPerson?.designation)
            setMaster.put("customer_contact_person_department",userInstance?.accsCustContPerson?.department)
            setMaster.put("customer_contact_person_mobileNo",userInstance?.accsCustContPerson?.mobileNo)
            setMaster.put("customer_contact_person_email",userInstance?.accsCustContPerson?.email)


        }else{
             return ["Message":"Data not found"]
        }

        return setMaster

    }

}

Step3

Add all access permission of the follows url:

/controllerName/uktoken      
/controllerName/customerInfoById/*

Note: Restfull api response always aspect the following parameters that why we use cors plugis in grails

        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, '*')   // to access all domain from client side
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, 'GET, OPTIONS')
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, 'Origin, Accept, Content-Type, X-Requested-With, Authorization')
        response.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, '3600')
        

How to call Api in grails:

package com.allClass.lps.tesco

import com.allClass.common.CommonConstant
import com.allClass.common.DbRelated
import com.allClass.common.DocumentPlacementDetailService
import grails.converters.JSON
import grails.transaction.Transactional
import org.grails.web.json.JSONObject

@Transactional(readOnly = true)
class AiController {

   
    def apiUrl ="http://ip:5000"
    DocumentPlacementDetailService documentPlacementDetailService
    def aiService
    def dataSource

    def pdfFileLocation ="E:\\allserver\\tomcat\\tomcat_8.5.39_64_6060\\webapps\\ai_pdf\\"   
    def downloadUrl ="http://ip:6060/ai_pdf"                                  

   
    def aiForNonRfid(){

         def resultData
         def responData
         def pdfPath
         def serverStsObj
         HashMap serverRes
         String message
         def ukDataSource
             ukDataSource = dataSource
             LpsCommonReportForTescoController lpsCommonReportForTesco = new LpsCommonReportForTescoController()
             responData = params


            Long id = params.getLong("nonRfiId")
            Long productRefId = params.getLong("productRefId")
            String woolmarkLogo = params.woolmarkLogo
            Long productBenifit = params.getLong("productBenifit")
            Long mmBenifit = params.getLong("mmBenifit")
            Long optionsId = params.getLong("optionsId")


        if(id !="" && productRefId !=""){
            resultData = lpsCommonReportForTesco.aiNonRfIdReport(id,productRefId,woolmarkLogo,productBenifit,mmBenifit,optionsId,ukDataSource,pdfFileLocation)


        }

        if(resultData){

            serverStsObj = this.apiCheckServerSts()
            if(serverStsObj.message == "Server Available"){
                
                serverRes = this.apiForPdfToAi(resultData)

                for (String key : serverRes.keySet()) {
                    message = serverRes.get(key);
                }

                if(message !="Bad Request"){
                    render(["url":message] as JSON)
                }else{
                    render(["url":"server_request_fail"] as JSON)
                }

            }else if(serverStsObj.message == "The server is busy processing another file please try again"){
                render(["url":"server_busy"] as JSON)
            }
        }else{
            render(["url":"no_pdf_layout_found"] as JSON)
        }


    }

    def apiCheckServerSts() {
        def jsonObject
        String output
        URL url = new URL(apiUrl + "/serverStatus");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        while ((output = br.readLine()) != null) {
            jsonObject = new JSONObject(output)
            
        }

        return jsonObject

    }

    def apiForPdfToAi(def resultData){

        def pdfFileUrl
        def jsonObject
        BufferedReader brr
        String responseLine
        responseLine = null;

        HashMap responseData = new HashMap()


        if(resultData){

           pdfFileUrl = downloadUrl+"/"+resultData   // for online bol
            

          URL url = new URL(apiUrl + "/upload/path");
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("POST")
          conn.setRequestProperty("Content-Type", "application/json");
          conn.setRequestProperty("Accept", "application/json");
          conn.setConnectTimeout(600000);                             // 1000 milliseconds = 1 seconds
          conn.setReadTimeout(600000);
          conn.setDoOutput(true);                                     // to set json data

          String jsonInputString = "{\"url\":\"${pdfFileUrl}\"}";


            OutputStream os = conn.getOutputStream();                 // setting up send
                                                                      // Copy content 'JSON' into
            os.write(jsonInputString.getBytes());
            System.out.println("Os output stream" + os.toString());
                                                                       // clean up
            os.flush();
            os.close();


            if (conn.getResponseCode() == 201) {                        // 201 == create and next created a new resource

                brr = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                

                while ((responseLine = brr.readLine()) != null) {
                    
                    jsonObject = new JSONObject(responseLine.trim())
                    responseData.put("message",jsonObject.message)
                }

            }else{

                responseData.put("message","Bad Request")
                System.out.println("Bad Request");
            }

        }

        return responseData

    }

}

How to to check Grails API

Open browser and enter the link

local:

http://localhost:1971/erp/transitStickerApi/customerInfoById/188    // ok

online:
http://domain/erp/transitStickerApi/customerInfoById/222

Open cmd and write the following code

local:

curl -i -H "Accept: application/json" localhost:1971/erp/transitStickerApi/customerInfoById/188   // ok

curl -H "Origin: http://localhost" --verbose localhost:1971/erp/transitStickerApi/customerInfoById/188  // ok

online:

curl -i -H "Accept: application/json" http://domain/erp/transitStickerApi/customerInfoById/222

curl -H "Origin: http://localhost" --verbose http://domain/erp/transitStickerApi/customerInfoById/222  // ok

bONEandALL
Visitor

Total : 20171

Today :18

Today Visit Country :

  • China
  • United States
  • United Kingdom
  • Portugal
  • Canada
  • Russia