Whatever message this page gives is out now! Go check it out!
url = "server URL" charset = "character encoding" clientCert = "filename" clientCertPassword = "password" columns = "query columns" delimiter = "character" file = "filename" firstrowasheaders = "yes|no" getAsBinary = "auto|yes|no|never" method = "method name" multipart = "yes|no" name = "query name" password = "password" path = "path" pool="HTTP connection pool" port = "port number" proxyServer = "host name" proxyPort = "port number" proxyUser = "username" proxyPassword = "password" redirect = "yes|no" resolveURL = "yes|no" result = "result name" textQualifier = "character" throwOnError = "yes|no" timeout = "time-out period in seconds" username = "username" userAgent = "user agent" authType = "BASIC|NTLM" domain = "domain name" usePool="yes|no" workstation = "workstation name"> cfhttpparam tags [optional for some methods] </cfhttp> |
Attribute | Req/Opt | Default | Description |
url | Required | Uses the http protocol | Address of the resource on the server that handles the request. The URL must include the hostname or IP address. If you do not specify the transaction protocol ( http :// or ), ColdFusion uses the default protocol, http . If you specify a port number in this attribute, it overrides any port attribute value. The cfhttpparam tag URL attribute appends query string attribute-value pairs to the URL. |
charset | Optional | For request: UTF-8 For response : charset specified by response Content-Type header, or UTF-8 if response does not specify charset . | The character encoding of the request, including the URL query string and form or file data, and the response. The following list includes commonly used values:
|
clientCert | Optional | The full path to a PKCS12 format file that contains the client certificate for the request. | |
clientCertPassword | Optional | Password used to decrypt the client certificate. | |
compression | Optional | The target webserver's compression status. The only supported value is none. If the target website runs on IIS with HTTP compression enabled, use this attribute to avoid a connection failure while performing GET or POST operations. | |
| file | Required if path is specified and not a GET method | Name of the file in which to store the response body. For a GET operation, the default is the file requested in the URL, if there is one. For example, if the URL in a GET method is http:www.myco.com/test.htm, the default file is test.htm. Do not specify the path to the directory in this attribute; use the path attribute. | |
| path | Required if file is specified. | Tells ColdFusion to save the HTTP response body in a file. Contains the absolute path to the directory in which to store the file. | |
getAsBinary | Optional | no |
|
method | Optional | GET |
|
| multipart | Optional | no (Sends as multipart only if request includes File type data.) | Note: The following attribute is used with the PUT method to determine how to send data specified with httpparam type="formField". Tells ColdFusion to send all data specified by cfhttpparam type="formField" tags as multipart form data, with a Content-Type of multipart/form-data. By default, ColdFusion sends cfhttp requests that contain only formField data with a Content Type of application/x-www-form- urlencoded . (If the request also includes File type data, ColdFusion uses the multipart/form-data content type for all parts.) If yes, ColdFusion also sends the request's charset in each Content-Type description. All form field data must be encoded in this character encoding, and ColdFusion does not URLEncode the data. (The field name must be in ISO-88591-1 or ASCII.) Some http parsers, including the one used by previous versions of ColdFusion, ignore the multipart form field character encoding description. |
| multipartType | Optional | form-data | Note: The attribute sets a multipart header field and is used, for example, for uploading videos on YouTube. The attribute allows you to set the multipart header field to related or form-data. By default, the value is form-data. |
password | Optional | Use to pass a password to the target URL for Basic Authentication. Combined with username to form a base64 encoded string that is passed in the Authenticate header. Does not provide support for Integrated Windows or Kerebos authentication. | |
port | Optional | 80 for http or 443 for https | Port number on the server to which to send the request. A port value in the url attribute overrides this value. |
proxyServer | Optional | Host name or IP address of a proxy server to which to send the request. | |
proxyPort | Optional | 80 | Port number to use on the proxy server. |
proxyUser | Optional | User name to provide to the proxy server. | |
proxyPassword | Optional | Password to provide to the proxy server. | |
| pool | Optional | List of connections to make HTTP requests. | |
| usePool | Optional | True or False | |
| result | Optional | Specifies the name of the variable in which you want the result returned. | |
redirect | Optional | yes | If the response header includes a Location field AND ColdFusion receives a 300-series (redirection) status code, specifies whether to redirect execution to the URL specified in the field:
|
resolveURL | Optional | no |
|
result | Optional | Lets you specify an alternate variable in which to receive a result. | |
throwOnError | Optional | no |
|
timeout | Optional | Value, in seconds, that is the maximum time the request can take. If the time-out passes without a response, ColdFusion considers the request to have failed. If the client specifies a time-out in the URL search parameter (for example, ?RequestTime=120) ColdFusion uses the lesser of the URL time-out and the timeout attribute value; this ensures that the request times out before, or at the same time as, the page. If the URL does not specify a time-out, ColdFusion uses the lesser of the Administrator time-out and the timeout attribute value. If the time-out is not set in any of these, ColdFusion waits indefinitely for the cfhttp request to process. | |
userAgent | Optional | ColdFusion | Text to put in the user agent request header. Used to identify the request client software. Can make the ColdFusion application appear to be a browser. |
username | Optional | Use to pass a user name to the target URL for Basic Authentication. Combined with password to form a base64 encoded string that is passed in the Authenticate header. Does not provide support for Integrated Windows or Kerberos authentication. | |
| authType | Optional | BASIC | The supported values are:
Note When authentication type is NTLM, do not set the redirect as false. |
| domain | Optional | The domain name for authentication. (Use for NTLM-based authentication) | |
| workstation | Optional | The workstation name for authentication. (Use for NTLM-based authentication) |
<!--- Get Video --->
<cfset videoName = "<video path>\hello.wmv">
<cfset videoFileName = "hello.wmv">
<cfoutput>
<!--- Set User Account Data --->
<cfset clientKey = "client key from google"/>
<cfset devKey = "<dev key from google>"/>
<cfset youTubeUploadURL = "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads"/>
<!--- Authenticate with Google / YouTube --->
<cfhttp url="https://www.google.com/accounts/ClientLogin" method="post" result="result" charset="utf-8">
<cfhttpparam type="formfield" name="accountType" value="HOSTED_OR_GOOGLE">
<cfhttpparam type="formfield" name="Email" value="<gmail id>">
<cfhttpparam type="formfield" name="Passwd" value="<password>">
<cfhttpparam type="formfield" name="service" value="youtube">
<cfhttpparam type="formfield" name="source" value="youtubecode">
</cfhttp>
<!--- Create Auth Token --->
<cfset content = result.filecontent>
<cfset authdata = structNew()>
<cfloop index="line" list="#content#" delimiters="#chr(10)#">
<cfset dtype = listFirst(line, "=")>
<cfset value = listRest(line, "=")>
<cfset authdata[dtype] = value></cfloop>
<!--- Create ATOM XML and save to a file to be sent with video --->
<cfsavecontent variable="meta"><cfoutput>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<media:group>
<media:title type="plain">WithOutQuotes</media:title>
<media:description type="plain">Test Description</media:description>
<media:category
scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People
</media:category>
<media:keywords>yourvideo</media:keywords>
</media:group>
</entry>
</cfoutput>
</cfsavecontent>
<cfset tmpfile = expandPath("./meta.xml")/>
<cffile action="write" file="#tmpfile#" output="#trim(meta)#" />
<!--- Upload video --->
<cfhttp url="#youTubeUploadURL#" result="result" method="POST" timeout="450" multipartType="related">
<cfhttpparam type="header" name="Authorization" value="GoogleLogin auth=#authdata.auth#">
<cfhttpparam type="header" name="X-GData-Client" value="#variables.clientkey#">
<cfhttpparam type="header" name="X-GData-Key" value="key=#variables.devkey#">
<cfhttpparam type="header" name="Slug" value="#videoFileName#">
<!---<CFHTTPPARAM type="HEADER" name="Connection" value="Keep-Alive"> --->
<!--- Send 2 files --->
<cfhttpparam type="file" name="API_XML_Request" file="#tmpfile#"
mimetype="application/atom+xml">
<cfhttpparam type="file" name="file" file="#videoName#" mimetype="video/*">
</cfhttp>
<cfdump var="#result#"/>
</cfoutput>Attribute | Req/Opt | Default | Description |
result | Optional | Specifies the name of the variable in which you want the result returned. |
Attribute | Req/Opt | Default | Description |
file | Required if path is specified and not a GET method | See Description | Name of the file in which to store the response body. For a GET operation, the default is the file requested in the URL, if there is one. For example, if the URL in a GET method is http:www.myco.com/test.htm, the default file is test.htm. Do not specify the path to the directory in this attribute; use the path attribute. |
path | Required if file is specified. | Tells ColdFusion to save the HTTP response body in a file. Contains the absolute path to the directory in which to store the file. |
ram:///filepath |
Attribute | Req/Opt | Default | Description |
columns | Optional | First row of response contains column names. | The column names for the query, separated by commas, with no spaces. Column names must start with a letter. The remaining characters can be letters, numbers, or underscore characters (_). If there are no column name headers in the response, specify this attribute to identify the column names. If you specify this attribute, and the firstrowasHeader attribute is True (the default), the column names specified by this attribute replace the first line of the response. You can use this behavior to replace the column names retrieved by the request with your own names. If a duplicate column heading is encountered in either this attribute or in the column names from the response, ColdFusion appends an underscore to the name to make it unique. If the number of columns specified by this attribute does not equal the number of columns in the HTTP response body, ColdFusion generates an error. |
delimiter | Optional | , (comma) | A character that separates query columns. The response body must use this character to separate the query columns. |
firstrowasheaders | Optional | yes | Determines how ColdFusion processes the first row of the query record set:
|
name | Optional | Tells ColdFusion to create a query object with the given name from the returned HTTP response body. | |
textQualifier | Optional | " double-quotation mark | A character that, optionally, specifies the start and end of a text column. This character must surround any text fields in the response body that contain the delimiter character as part of the field value. To include this character in column text, escape it by using two characters in place of one. For example, if the qualifier is a double-quotation mark, escape it as "". |
Name | Description |
cfhttp.charSet | Response character character set (character encoding) specified by the response Content-Type header. |
cfhttp.errorDetail | If the connection to the HTTP server fails, contains details about the failure. For instance: "Unknown host: my.co.com"; otherwise, the empty string. recommends that you check this variable for an error condition before checking other variables. |
cfhttp.fileContent | Response body; for example, the contents of an html page retrieved by a GET operation. Empty if you save the response in a file. |
cfhttp.header | Raw response header containing all header information in a single string. Contains the same information as the cfhttp.responseHeader variable. |
cfhttp.mimeType | MIME type specified by the response Content-Type header; for example, text/html. |
cfhttp.responseHeader | The response headers formatted into a structure. Each element key is the header name, such as Content-Type or Status_Code. If there is more than one instance of a header type, the type values are put in an array. One common technique is to dynamically access the cfhttp.responseHeader structure as a dynamic array; for example, #cfhttp.resonseHeaderfieldVariable#. |
cfhttp.statusCode | The HTTP status_code header value followed by the HTTP Explanation header value; for example, "200 OK". |
cfhttp.text | Boolean; true if the response body content type is text. ColdFusion recognizes the response body as text in the following situations:
|
Field1,Field2,Field3 "A comma, in text","A quote: ""Oh My!""",Plain text |
<cfhttp method="Get"
url="127.0.0.1:8500/tests/escapetest.txt"
name="onerow">
<cfdump var="#onerow#"><br><cfhttp result="result" method="GET" charset="utf-8" url="https://www.adobe.com/">
<cfhttpparam name="q" type="formfield" value="cfml">
</cfhttp>
<cfdump var="#result#"><cfscript>
// API Configuration
apiBaseURL = "https://api.example-supplier.com/v1";
apiKey = "your-api-key-here"; // In production, store securely in application scope
productID = 12345;
// Check if we should make real API calls
useRealAPI = isDefined("url.realAPI") AND url.realAPI;
</cfscript>
<h2>REST API Integration - Product Information</h2>
<cfif NOT useRealAPI>
<div style="background: ##fff3e0; border: 2px solid ##ff9800; padding: 15px; margin: 15px 0; border-radius: 5px;">
<h4>📝 Demo Mode</h4>
<p>This example uses mock data for demonstration. To make real API calls:</p>
<ol>
<li>Configure your API credentials in the code</li>
<li>Add <code>?realAPI=true</code> to the URL</li>
</ol>
</div>
</cfif>
<!--- Make GET request to fetch product data (or use mock data) --->
<cfif useRealAPI>
<cfhttp
method="GET"
url="#apiBaseURL#/products/#productID#"
result="apiResult"
timeout="10"
charset="utf-8">
<!--- Add authentication header --->
<cfhttpparam
type="header"
name="Authorization"
value="Bearer #apiKey#">
<!--- Add content type header --->
<cfhttpparam
type="header"
name="Accept"
value="application/json">
</cfhttp>
<cfelse>
<!--- Create mock API response for demonstration --->
<cfscript>
apiResult = {
"statusCode": "200 OK",
"fileContent": serializeJSON({
"id": productID,
"name": "Premium Wireless Headphones",
"sku": "WHD-2024-PRO",
"price": 299.99,
"quantity": 47,
"description": "High-quality wireless headphones with active noise cancellation and 30-hour battery life.",
"category": "Electronics",
"manufacturer": "AudioTech Pro",
"inStock": true
}),
"responseHeader": {
"Content-Type": "application/json",
"Response-Time": "45ms"
},
"mimeType": "application/json",
"charset": "utf-8"
};
</cfscript>
</cfif>
<!--- Display the complete API response for debugging --->
<h3>API Response Details</h3>
<cfdump
var="#apiResult#"
label="Complete API Response"
expand="no">
<hr>
<!--- Check if the request was successful --->
<cfif apiResult.statusCode EQ "200 OK">
<h3 style="color: green;">✓ API Request Successful</h3>
<!--- Parse JSON response --->
<cfscript>
// Convert JSON string to ColdFusion structure
productData = deserializeJSON(apiResult.fileContent);
</cfscript>
<!--- Display parsed product data --->
<h3>Product Information</h3>
<cfdump
var="#productData#"
label="Parsed Product Data"
expand="yes">
<!--- Display product in user-friendly format --->
<div style="border: 1px solid #ccc; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h2>#productData.name#</h2>
<p><strong>SKU:</strong> #productData.sku#</p>
<p><strong>Price:</strong> $#numberFormat(productData.price, "0.00")#</p>
<p><strong>In Stock:</strong> #productData.quantity# units</p>
<p><strong>Description:</strong> #productData.description#</p>
</div>
<!--- Performance metrics --->
<cfscript>
performanceInfo = {
"responseTime": apiResult.responseHeader["Response-Time"] ?: "N/A",
"contentLength": len(apiResult.fileContent) & " bytes",
"statusCode": apiResult.statusCode,
"mimeType": apiResult.mimeType
};
</cfscript>
<h3>API Performance Metrics</h3>
<cfdump var="#performanceInfo#" label="Performance Info">
<cfelse>
<!--- Handle error responses --->
<h3 style="color: red;">✗ API Request Failed</h3>
<cfscript>
errorInfo = {
"statusCode": apiResult.statusCode,
"errorMessage": apiResult.statusCode contains "404" ? "Product not found" : "API request failed",
"responseBody": apiResult.fileContent
};
</cfscript>
<cfdump
var="#errorInfo#"
label="Error Details"
expand="yes">
<div style="background: ##ffebee; border: 1px solid ##f44336; padding: 15px; margin: 20px 0; border-radius: 5px;">
<p><strong>Error:</strong> Unable to retrieve product information.</p>
<p><strong>Status:</strong> #apiResult.statusCode#</p>
<p>Please try again later or contact support.</p>
</div>
</cfif>
<!--- Example: Making multiple API calls --->
<h3>Batch API Requests (Multiple Products)</h3>
<cfscript>
productIDs = [12345, 12346, 12347];
products = [];
for (id in productIDs) {
// Simulate API call (in real scenario, this would be actual API calls)
mockProduct = {
"id": id,
"name": "Product " & id,
"sku": "SKU-" & id,
"price": randRange(10, 100),
"quantity": randRange(0, 50),
"status": "active"
};
arrayAppend(products, mockProduct);
}
</cfscript>
<cfdump
var="#products#"
label="Multiple Products Retrieved"
expand="yes">
<!--- Example: POST request to create a new product --->
<cfif isDefined("url.testPost")>
<h3>Example: POST Request to Create Product</h3>
<cfscript>
// Create product data to send
newProduct = {
"name": "New Product",
"sku": "NEW-SKU-001",
"price": 49.99,
"quantity": 100,
"description": "A new product created via API"
};
// Convert to JSON
jsonPayload = serializeJSON(newProduct);
</cfscript>
<cfhttp
method="POST"
url="#apiBaseURL#/products"
result="createResult"
timeout="10"
charset="utf-8">
<!--- Authentication --->
<cfhttpparam
type="header"
name="Authorization"
value="Bearer #apiKey#">
<!--- Content type --->
<cfhttpparam
type="header"
name="Content-Type"
value="application/json">
<!--- JSON body --->
<cfhttpparam
type="body"
value="#jsonPayload#">
</cfhttp>
<cfdump
var="#createResult#"
label="POST Request Result"
expand="yes">
</cfif><cfscript>
// Payment Gateway Configuration
gatewayURL = "https://api.payment-gateway.com/v1/charges";
merchantID = "merchant_123456";
apiSecretKey = "sk_test_your_secret_key"; // Store securely!
// Check if we should make real payment calls
useRealPayment = isDefined("url.realPayment") AND url.realPayment;
// Transaction details
transactionData = {
"amount": 99.99,
"currency": "USD",
"description": "Order ##12345 - Laptop Computer",
"customer": {
"email": "customer@example.com",
"name": "John Smith"
},
"payment_method": {
"card_token": "tok_visa_4242424242424242", // Token from secure form
"billing_address": {
"line1": "123 Main Street",
"city": "San Francisco",
"state": "CA",
"postal_code": "94102"
}
},
"metadata": {
"order_id": "12345",
"customer_id": "67890"
}
};
// Convert to JSON
jsonPayload = serializeJSON(transactionData);
</cfscript>
<h2>Payment Gateway Integration</h2>
<!--- Display transaction details being sent --->
<h3>Transaction Details</h3>
<cfdump
var="#transactionData#"
label="Payment Request Data"
expand="yes"
hide="payment_method">
<hr>
<!--- Send payment request to gateway (or use mock data) --->
<cfif useRealPayment>
<cfhttp
method="POST"
url="#gatewayURL#"
result="paymentResult"
timeout="30"
charset="utf-8">
<!--- Authentication using API key --->
<cfhttpparam
type="header"
name="Authorization"
value="Bearer #apiSecretKey#">
<!--- Content type --->
<cfhttpparam
type="header"
name="Content-Type"
value="application/json">
<!--- Merchant ID header --->
<cfhttpparam
type="header"
name="X-Merchant-ID"
value="#merchantID#">
<!--- JSON payload --->
<cfhttpparam
type="body"
value="#jsonPayload#">
</cfhttp>
<cfelse>
<!--- Create mock payment response --->
<cfscript>
paymentResult = {
"statusCode": "200 OK",
"fileContent": serializeJSON({
"id": "ch_" & createUUID(),
"status": "succeeded",
"amount": 9999,
"currency": "usd",
"payment_method": {
"last4": "4242",
"brand": "visa"
},
"receipt_number": "RCPT-" & randRange(100000, 999999)
}),
"responseHeader": {
"Content-Type": "application/json"
},
"mimeType": "application/json"
};
</cfscript>
</cfif>
<!--- Display complete gateway response --->
<h3>Payment Gateway Response</h3>
<cfdump
var="#paymentResult#"
label="Complete Gateway Response"
expand="no">
<hr>
<!--- Process the payment response --->
<cfif paymentResult.statusCode EQ "200 OK" OR paymentResult.statusCode EQ "201 Created">
<!--- Parse the response --->
<cfscript>
paymentResponse = deserializeJSON(paymentResult.fileContent);
</cfscript>
<!--- Check if payment was successful --->
<cfif structKeyExists(paymentResponse, "status") AND paymentResponse.status EQ "succeeded">
<h3 style="color: green;">✓ Payment Successful</h3>
<div style="background: ##e8f5e9; border: 2px solid ##4caf50; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h2>Payment Confirmed!</h2>
<p><strong>Transaction ID:</strong> #paymentResponse.id#</p>
<p><strong>Amount Charged:</strong> $#numberFormat(paymentResponse.amount / 100, "0.00")#</p>
<p><strong>Card Last 4:</strong> ****#paymentResponse.payment_method.last4#</p>
<p><strong>Receipt Number:</strong> #paymentResponse.receipt_number#</p>
<p><strong>Status:</strong> #uCase(paymentResponse.status)#</p>
</div>
<!--- Display transaction details --->
<h3>Transaction Details</h3>
<cfdump
var="#paymentResponse#"
label="Payment Response"
expand="yes">
<!--- Log transaction (in production, save to database) --->
<cfscript>
transactionLog = {
"timestamp": now(),
"transaction_id": paymentResponse.id,
"amount": paymentResponse.amount / 100,
"currency": paymentResponse.currency,
"status": paymentResponse.status,
"customer_email": transactionData.customer.email,
"order_id": transactionData.metadata.order_id
};
</cfscript>
<h3>Transaction Log Entry</h3>
<cfdump
var="#transactionLog#"
label="Transaction to be saved"
expand="yes">
<cfelse>
<!--- Payment was declined or failed --->
<h3 style="color: orange;">⚠ Payment Declined</h3>
<cfscript>
declineReason = structKeyExists(paymentResponse, "failure_message") ?
paymentResponse.failure_message : "Payment declined by card issuer";
</cfscript>
<div style="background: ##fff3e0; border: 2px solid ##ff9800; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h2>Payment Could Not Be Processed</h2>
<p><strong>Reason:</strong> #declineReason#</p>
<p><strong>Status:</strong> #paymentResponse.status#</p>
<p>Please check your payment information and try again.</p>
</div>
<cfdump
var="#paymentResponse#"
label="Decline Details"
expand="yes">
</cfif>
<cfelse>
<!--- HTTP error occurred --->
<h3 style="color: red;">✗ Payment Request Failed</h3>
<div style="background: ##ffebee; border: 2px solid ##f44336; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h2>Payment Processing Error</h2>
<p><strong>Status:</strong> #paymentResult.statusCode#</p>
<p>Unable to connect to payment gateway. Please try again later.</p>
</div>
<cfscript>
errorDetails = {
"statusCode": paymentResult.statusCode,
"errorResponse": paymentResult.fileContent,
"timestamp": now()
};
</cfscript>
<cfdump
var="#errorDetails#"
label="Error Information"
expand="yes">
</cfif>
<!--- Example: Refund processing --->
<cfif isDefined("url.testRefund")>
<h3>Example: Processing a Refund</h3>
<cfscript>
refundData = {
"charge_id": "ch_1234567890",
"amount": 99.99,
"reason": "customer_request"
};
refundPayload = serializeJSON(refundData);
</cfscript>
<cfhttp
method="POST"
url="https://api.payment-gateway.com/v1/refunds"
result="refundResult"
timeout="30">
<cfhttpparam
type="header"
name="Authorization"
value="Bearer #apiSecretKey#">
<cfhttpparam
type="header"
name="Content-Type"
value="application/json">
<cfhttpparam
type="body"
value="#refundPayload#">
</cfhttp>
<cfdump
var="#refundResult#"
label="Refund Response"
expand="yes">
</cfif><cfscript>
// Weather API Configuration
weatherAPIURL = "https://api.weather-service.com/v2.5/weather";
weatherAPIKey = "your_weather_api_key_here";
// Location to query (can be city name or coordinates)
cityName = "San Francisco";
units = "imperial"; // imperial for Fahrenheit, metric for Celsius
// Check if we should make real API calls
useRealWeather = isDefined("url.realWeather") AND url.realWeather;
</cfscript>
<h2>Weather Data Service Integration</h2>
<!--- Fetch current weather data (or use mock data) --->
<cfif useRealWeather>
<cfhttp
method="GET"
url="#weatherAPIURL#"
result="weatherResult"
timeout="15"
charset="utf-8">
<!--- City name parameter --->
<cfhttpparam
type="url"
name="q"
value="#cityName#">
<!--- API key parameter --->
<cfhttpparam
type="url"
name="appid"
value="#weatherAPIKey#">
<!--- Units parameter --->
<cfhttpparam
type="url"
name="units"
value="#units#">
<!--- Response format --->
<cfhttpparam
type="url"
name="mode"
value="json">
</cfhttp>
<cfelse>
<!--- Create mock weather response --->
<cfscript>
weatherResult = {
"statusCode": "200 OK",
"fileContent": serializeJSON({
"name": cityName,
"sys": {"country": "US"},
"main": {
"temp": 68.5,
"feels_like": 65.2,
"temp_min": 62.0,
"temp_max": 75.0,
"humidity": 65
},
"weather": [
{
"description": "partly cloudy",
"main": "Clouds"
}
],
"wind": {"speed": 8.5},
"clouds": {"all": 40}
}),
"responseHeader": {
"Content-Type": "application/json"
},
"mimeType": "application/json"
};
</cfscript>
</cfif>
<!--- Display raw API response --->
<h3>API Response Details</h3>
<cfdump
var="#weatherResult#"
label="Weather API Response"
expand="no">
<hr>
<!--- Check if request was successful --->
<cfif weatherResult.statusCode EQ "200 OK">
<!--- Parse weather data --->
<cfscript>
weatherData = deserializeJSON(weatherResult.fileContent);
// Extract key weather information
currentWeather = {
"location": weatherData.name & ", " & weatherData.sys.country,
"temperature": numberFormat(weatherData.main.temp, "0.0") & "°F",
"feels_like": numberFormat(weatherData.main.feels_like, "0.0") & "°F",
"description": weatherData.weather[1].description,
"humidity": weatherData.main.humidity & "%",
"wind_speed": numberFormat(weatherData.wind.speed, "0.0") & " mph",
"clouds": weatherData.clouds.all & "%",
"timestamp": dateTimeFormat(now(), "yyyy-mm-dd HH:nn:ss")
};
// Temperature ranges
tempInfo = {
"current": weatherData.main.temp,
"min": weatherData.main.temp_min,
"max": weatherData.main.temp_max,
"feels_like": weatherData.main.feels_like
};
</cfscript>
<h3 style="color: green;">✓ Weather Data Retrieved Successfully</h3>
<!--- Display user-friendly weather card --->
<div style="background: linear-gradient(135deg, ##667eea 0%, ##764ba2 100%); color: white; padding: 30px; margin: 20px 0; border-radius: 10px; box-shadow: 0 10px 20px rgba(0,0,0,0.2);">
<h1 style="margin: 0; color: white;">🌤️ #weatherData.name#, #weatherData.sys.country#</h1>
<h2 style="margin: 10px 0; color: white; font-size: 48px;">
#numberFormat(weatherData.main.temp, "0")#°F
</h2>
<p style="font-size: 20px; margin: 10px 0; text-transform: capitalize;">
#weatherData.weather[1].description#
</p>
<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin-top: 20px;">
<div>
<strong>Feels Like:</strong> #numberFormat(weatherData.main.feels_like, "0")#°F
</div>
<div>
<strong>Humidity:</strong> #weatherData.main.humidity#%
</div>
<div>
<strong>Wind:</strong> #numberFormat(weatherData.wind.speed, "0.0")# mph
</div>
<div>
<strong>Clouds:</strong> #weatherData.clouds.all#%
</div>
</div>
</div>
<!--- Display structured weather data --->
<h3>Current Weather Information</h3>
<cfdump
var="#currentWeather#"
label="Formatted Weather Data"
expand="yes">
<h3>Temperature Details</h3>
<cfdump
var="#tempInfo#"
label="Temperature Information"
expand="yes">
<!--- Display complete parsed data --->
<h3>Complete Weather Response</h3>
<cfdump
var="#weatherData#"
label="Full Weather Data Object"
expand="no">
<!--- Cache example --->
<cfscript>
// In production, cache this data to reduce API calls
cacheDuration = createTimeSpan(0, 0, 30, 0); // 30 minutes
cacheKey = "weather_" & cityName;
// Store in cache (pseudo-code)
// cachePut(cacheKey, weatherData, cacheDuration);
cacheInfo = {
"cacheKey": cacheKey,
"cacheDuration": "30 minutes",
"shouldCache": true,
"reason": "Weather data doesn't change frequently"
};
</cfscript>
<h3>Caching Strategy</h3>
<cfdump
var="#cacheInfo#"
label="Cache Configuration"
expand="yes">
<cfelse>
<!--- Handle API errors --->
<h3 style="color: red;">✗ Weather Data Request Failed</h3>
<cfscript>
errorResponse = {
"statusCode": weatherResult.statusCode,
"errorBody": weatherResult.fileContent,
"city": cityName
};
// Try to parse error message
try {
errorData = deserializeJSON(weatherResult.fileContent);
errorMessage = structKeyExists(errorData, "message") ? errorData.message : "Unknown error";
} catch (any e) {
errorMessage = "Unable to parse error response";
}
</cfscript>
<div style="background: ##ffebee; border: 2px solid ##f44336; padding: 20px; margin: 20px 0; border-radius: 5px;">
<h2>Weather Service Error</h2>
<p><strong>Status:</strong> #weatherResult.statusCode#</p>
<p><strong>Error:</strong> #errorMessage#</p>
<p>Unable to retrieve weather data for #cityName#. Please check the city name and try again.</p>
</div>
<cfdump
var="#errorResponse#"
label="Error Details"
expand="yes">
</cfif>
<!--- Example: Fetch weather for multiple cities --->
<h3>Multi-City Weather Query</h3>
<cfscript>
cities = ["New York", "Los Angeles", "Chicago", "Miami"];
weatherResults = [];
conditions = ["Sunny", "Cloudy", "Rainy", "Partly Cloudy"];
for (city in cities) {
// In real scenario, make actual API calls
// For demo, create mock data
mockWeather = {
"city": city,
"temperature": randRange(50, 90),
"condition": conditions[randRange(1, 4)],
"humidity": randRange(30, 80)
};
arrayAppend(weatherResults, mockWeather);
}
</cfscript>
<cfdump
var="#weatherResults#"
label="Weather for Multiple Cities"
expand="yes">
<!--- Example: Weather forecast request --->
<cfif isDefined("url.showForecast")>
<h3>5-Day Weather Forecast</h3>
<cfhttp
method="GET"
url="https://api.weather-service.com/v2.5/forecast"
result="forecastResult"
timeout="15">
<cfhttpparam type="url" name="q" value="#cityName#">
<cfhttpparam type="url" name="appid" value="#weatherAPIKey#">
<cfhttpparam type="url" name="units" value="#units#">
<cfhttpparam type="url" name="cnt" value="40"> <!--- 40 timestamps (5 days) --->
</cfhttp>
<cfdump
var="#forecastResult#"
label="5-Day Forecast Response"
expand="no">
<cfif forecastResult.statusCode EQ "200 OK">
<cfscript>
forecastData = deserializeJSON(forecastResult.fileContent);
</cfscript>
<cfdump
var="#forecastData#"
label="Forecast Data"
expand="yes"
top="3">
</cfif>
</cfif>