function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
James BuckelewJames Buckelew 

Apex http request from user input on LWC

I am trying to allow our Salesforce Users to paste a number into an input field, then let an Apex Class process a named Credential HTTP request - currently getting an error and not sure why. 

I will post the code below. 

Alternatively, this number they are inputting also exists on the account object but I'm struggling to pass that information through to the Apex class as well. (Prefill the input box with the number, or submit the request onClick with a button)

-- Apex Class --

public class samCall {

    @AuraEnabled(cacheable=true)

    public static String samQuery(Integer accountDuns) {

        HttpRequest req = new HttpRequest();
        req.setEndpoint( 'callout:samAPI' + accountDuns );
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        
        return res.getBody();

    }

}
-- HTML --
<template>
    <div >

        <lightning-input type="text" label="Enter DUNS" value={dunsNumber} onchange={handleChange}> </lightning-input>

        <p>Displaying SAM Information</p>

        <template if:true={samRecord}>
                <p> Name: {samRecord} </p>
        </template>

        <template if:true={error}>
            Some error occured.
        </template>
        
    </div>
</template>
-- JS --
import { LightningElement,wire,track,api } from 'lwc';

import getDuns from '@salesforce/apex/samCall.samQuery';
 

export default class searchSam extends LightningElement {

    @api dunsNumber;

    @track samRecord;

    @track error;

    handleChange(event){

        const userInput = event.target.value;

        this.dunsNumber = userInput;

    }

 

    @wire(getDuns,{ accountDuns: '$dunsNumber'}) 

    samData({ error, data }) {

        if (data) {

            //console.log('RecordId is'+recordId);

            this.samRecord = data;

            this.error = undefined;

        } else if (error) {

            //console.log('Error block');

            this.error = error;

            this.samRecord = undefined;

        }

    }

}

-- Meta --
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
            <target>lightning__RecordPage</target>
            <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>


 
Best Answer chosen by James Buckelew
James BuckelewJames Buckelew
public class sCall {

@AuraEnabled(cacheable=true)
public static string sQuery(string accountDs) {

    HttpRequest req = new HttpRequest();
    req.setEndpoint( 'callout:xxxxxxxx/urlinfo/v2/ents?yyyyyyy=' + accountDs);
    req.setHeader( 'X-Api-Key', '{!$Credential.Password}' );
    req.setMethod('GET');
    Http http = new Http();
    HTTPResponse res = http.send(req);

    entApi parsedResponse =  (entApi) JSON.deserialize(res.getBody(), entApi.class);

    Object entReg = parsedResponse.entData[0].entRegistration;

    String pretty = JSON.serialize(entReg);

    System.debug('Is this pretty? >>>' + ' ' + pretty);

    return pretty;

}
import { LightningElement,wire,track,api } from 'lwc';

import getD from '@salesforce/apex/samCall.sQuery';

export default class searchS extends LightningElement {

@api dNum;
@track sRecord;
@track error;
@track data;

    handleClick(event){

        let inputDuns = this.template.querySelector('lightning-input').value;

        this.dNum = inputD; //the input from html

    }

    @wire(getD,{ accountDuns: '$dNum'})
    
    sData({ error, data }) {

        if (data) {

            //console.log('RecordId is'+recordId);
            this.sRecord = JSON.parse(data);

            this.error = undefined;

        } else if (error) {

            //console.log('Error block');
            this.error = error;

            this.samRecord = undefined;

        }

    }

 }
<template>
<lightning-card title="Check Info" icon-name="custom:custom63">
        <lightning-input type="text" label="Enter Number" value={dNum}> </lightning-input>
            <lightning-button label="Check" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
            
            <p>Displaying Information</p>
            Input: {dNum}


            <template if:true={sRecord}>
                <p>Name: {sRecord.xxxxxx} </p> //xxxxxxx is field name of returned array
            </template>
            <template if:true={error}>
                <p>1. Whoops! {error} </p>
            </template>

        </lightning-card>
</template>

 

All Answers

Yogendra JangidYogendra Jangid
Hi James,
Looking at your code, it seems you are using integer parameter in method defined in apex class whereas the lightning-input in your LWC is of type text. So there is type mismatch, you would like to consider both as either text or number. Making this change should work for you.
In case you are going with text/string type both side, consider converting the string parameter to integer first before passing in the callout request.

Hope this answers your question, if so please can you mark this as best answer. Many thanks
James BuckelewJames Buckelew

It appears to be an issue with the Callout from the names credential. My understanding was the callout would provide the URL from the named credential and then append the user input to the end of that URL, but it is not doing that. 

14:01:42.0 (2973824)|CALLOUT_REQUEST|[11]|System.HttpRequest[Endpoint=callout:samAPI81203555, Method=GET]
14:01:42.9 (9284370)|NAMED_CREDENTIAL_RESPONSE|NamedCallout[Named Credential Id=null, Named Credential Name=null, Status Code=0, Response Size bytes=0, Overall Callout Time ms=0, Connect Time ms=0
14:01:42.0 (10096261)|EXCEPTION_THROWN|[11]|System.CalloutException: The callout couldn't access the endpoint. You might not have the required permissions, or the named credential "samAPI81203555" might not exist.
14:01:42.0 (10216471)|HEAP_ALLOCATE|[11]|Bytes:148
14:01:42.0 (10333226)|FATAL_ERROR|System.CalloutException: The callout couldn't access the endpoint. You might not have the required permissions, or the named credential "samAPI81203555" might not exist.

Class.samCall.samQuery: line 11, column 1
14:01:42.0 (10348365)|FATAL_ERROR|System.CalloutException: The callout couldn't access the endpoint. You might not have the required permissions, or the named credential "samAPI81203555" might not exist.
James BuckelewJames Buckelew
I have solved it. This can be closed. 
sakhisakhi
How did you solve it James , Was it a remote site settings miss .Please share for benefit of others .
James BuckelewJames Buckelew
public class sCall {

@AuraEnabled(cacheable=true)
public static string sQuery(string accountDs) {

    HttpRequest req = new HttpRequest();
    req.setEndpoint( 'callout:xxxxxxxx/urlinfo/v2/ents?yyyyyyy=' + accountDs);
    req.setHeader( 'X-Api-Key', '{!$Credential.Password}' );
    req.setMethod('GET');
    Http http = new Http();
    HTTPResponse res = http.send(req);

    entApi parsedResponse =  (entApi) JSON.deserialize(res.getBody(), entApi.class);

    Object entReg = parsedResponse.entData[0].entRegistration;

    String pretty = JSON.serialize(entReg);

    System.debug('Is this pretty? >>>' + ' ' + pretty);

    return pretty;

}
import { LightningElement,wire,track,api } from 'lwc';

import getD from '@salesforce/apex/samCall.sQuery';

export default class searchS extends LightningElement {

@api dNum;
@track sRecord;
@track error;
@track data;

    handleClick(event){

        let inputDuns = this.template.querySelector('lightning-input').value;

        this.dNum = inputD; //the input from html

    }

    @wire(getD,{ accountDuns: '$dNum'})
    
    sData({ error, data }) {

        if (data) {

            //console.log('RecordId is'+recordId);
            this.sRecord = JSON.parse(data);

            this.error = undefined;

        } else if (error) {

            //console.log('Error block');
            this.error = error;

            this.samRecord = undefined;

        }

    }

 }
<template>
<lightning-card title="Check Info" icon-name="custom:custom63">
        <lightning-input type="text" label="Enter Number" value={dNum}> </lightning-input>
            <lightning-button label="Check" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
            
            <p>Displaying Information</p>
            Input: {dNum}


            <template if:true={sRecord}>
                <p>Name: {sRecord.xxxxxx} </p> //xxxxxxx is field name of returned array
            </template>
            <template if:true={error}>
                <p>1. Whoops! {error} </p>
            </template>

        </lightning-card>
</template>

 
This was selected as the best answer