Reputation: 23
Can you please help me? I am trying to consume response in my ColdFusion application. Just wanted to try with this fake API before proceeding to the actual one.
I have created a component with two functions inside it. My cfc looks like this:
<cfcomponent displayname="test" hint="testing.." output="yes">
<cfsetting enablecfoutputonly="true" showdebugoutput="true">
<cffunction name="start" access="public" output="no" returntype="any" description="initialize the component">
<cfset variables.testUrl = "https://jsonplaceholder.typicode.com/posts">
<cfreturn this>
</cffunction>
<cffunction access="public" output="false" name="testGetReq" displayname="TestGetReq" description="testing" returntype="any">
<cfset variables.testUrl = "https://jsonplaceholder.typicode.com/posts">
<cfhttp
result="httpResponsetest"
url="#variables.testUrl#"
timeout="30"
method="get"
>
<cfhttpparam
type="header"
name="Content-Type"
value="application/json"
/>
</cfhttp>
</cfhttp>
<cfreturn httpResponsetest>
</cffunction>
</cfcomponent>
In my cfm page. I am trying to instantiate this component and print whatever I am getting as a response but I am not able to print anything out there.
<cfset testObj = CreateObject("component","usedGear_admin.cfc.photoUploadNew").testGetReq()>
<cfoutput >
#testObj#
</cfoutput>
Any help would be greatly appreciated.
Upvotes: 0
Views: 743
Reputation: 15846
I think you are using cfhttp
result wrong here. When we do a cfhttp
call,
<cfhttp
method="get"
result="httpResponsetest"
url="https://jsonplaceholder.typicode.com/posts"
timeout="30"
>
</cfhttp>
They try the following, you will see httpResponsetest
has multiple keys. The data provided by API will be present in httpResponsetest.fileContent
. Also most of the time there is Mimetype,Responseheader,Statuscode
etc.
<cfdump var="#httpResponsetest.fileContent#">
Here you can see the data is in JSON format. That means you'll need to deserialize them to be able to use it.
<cfdump var="#deserializeJSON(httpResponsetest.fileContent)#">
You can deserialize it and return from the function. Along with that you'll need to handle the case where API responds with am error.
Upvotes: 1