Wrapping a call to the Twitter user lookup API with ColdFusion

I just wrote a quick UDF (available now on CFLib) that wraps the call to Twitter’s user look up system. Like most Twitter APIs, this one is ridiculously simple, but I need this code for another project I’m working on (technically I need it in Flex, but the ColdFusion version helps me understand how I’ll write that) so I thought I’d write it up real quick like. Here is getTwitterUser:

<cffunction name="getTwitterUser" output="false" returnType="struct"> <cfargument name="screenname" type="string" required="true"> <cfset var httpResult = ""> <!--- remove the @ if they included it. ---> <cfif left(arguments.screenname,1) is "@"> <cfset arguments.screenname = right(arguments.screenname, len(arguments.screenname)-1)> </cfif> <cfset var theUrl = "http://api.twitter.com/1/users/show.json?screen_name=#arguments.screenname#"> <cfhttp url="#theUrl#" result="httpResult"> <cfset var result = deserializeJSON(httpResult.filecontent)> <cfreturn result> </cffunction>

I'd rather that be in script to be honest, but that wouldn't be difficult to rewrite. Usage then is pretty trivial. If you ask for a user that exists, you get a large structure back. If you get one that does not, you get an error key in the struct. Here's example code:

<cfset res = getTwitterUser("cfjedimaster")> <cfif structKeyExists(res, "name") and structKeyExists(res, "profile_image_url")> <cfoutput> <p> <img src="#res.profile_image_url#" align="left"> #res.name# <br clear="left"> </p> </cfoutput> </cfif> <cfdump var="#getTwitterUser('cfjedimaster221920')#">

And the result...

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments