Hey, Does someone know how to include api's throug...
# cfml-beginners
n
Hey, Does someone know how to include api's through a HTTP request and how do I communicate with it?
b
You mean like send an HTTP request to a remote REST API and get back the response?
I would start here https://cfdocs.org/cfhttp
s
most rest api docs will have a curl example, I usually look at that to determine how to set up my cfhttp requests. I also usually create a CFC that has a function for each of the api functions I want to implement. Each cfc function will take in whatever arguments the api method requires, build the json string and/or url parameters needed in the http request, then parse out the stuff I need from the http response into cf variables that get returned to the caller. Then the rest of my application can just call a CFC function to execute the API methods as needed.
n
do you have an example? @Scott Bennett
s
Copy code
component {

	this.apiKey = '#application.sparkpostAPIKey#';

	public function sendTransactionalEmail(required campaign_id, required string email_to, required string greeting_name, required string message_body, required string subject) {

		/* Generate Message Object */
		messageObject = {
			"campaign_id" = "#arguments.campaign_id#",
			"options" = {
				"open_tracking" = true,
				"click_tracking" = true
			},
			"recipients" = [
				{
					"address" = {"email" = "#arguments.email_to#", "name"="#arguments.greeting_name#"}, 
					"substitution_data": {
						"subject": "#arguments.subject#",
						"greeting_name": "#arguments.greeting_name#",
						"message_body": "#arguments.message_body#"
						}
				}
			],
			"content" = {
				"template_id":"transaction-email-template",
				"use_draft_template": false
			}
		};
		cfhttp( getasbinary="never", url="<https://api.sparkpost.com/api/v1/transmissions?num_rcpt_errors=3>", timeout=60, result="httpResp", method="post" ) {
			cfhttpparam( name="Content-Type", type="header", value="application/json" );
			cfhttpparam( name="Accept", type="header", value="application/json" );
			cfhttpparam( name="Authorization", type="header", value=this.APIKey );
			cfhttpparam( type="body", value=serializejson(messageObject) );
		}
		return deserializejson(httpResp.filecontent);
	}

}
that is a simplified version of a sparkpostapi.cfc I have (I took everything out but one function, and I tweaked it a bit to replace some things that were variables [like the endpoint url] for a more simple example)