Tcl HTTP Client Documentation

Working with HTTP requests in Tool Command Language

Overview

Tcl (Tool Command Language) provides robust HTTP client capabilities through the built-in http package. This documentation covers common patterns for making HTTP requests, handling responses, and debugging connectivity issues.

The http package has been part of Tcl since version 8.0 and provides a simple interface for web service integration.

Basic HTTP Request

Here's a simple example of making an HTTP GET request:

#!/usr/bin/env tclsh
package require http

# Make a simple GET request
set url "https://httpbin.org/get"
set token [::http::geturl $url]

# Check the response
set status [::http::status $token]
set data [::http::data $token]

puts "Status: $status"
puts "Response: $data"

# Clean up
::http::cleanup $token
Status: ok Response: { "args": {}, "headers": { "Host": "httpbin.org", "User-Agent": "Tcl http client package 2.9.5" }, "origin": "192.168.1.100", "url": "https://httpbin.org/get" }

Error Handling

Proper error handling is essential for robust HTTP clients:

#!/usr/bin/env tclsh
package require http

proc safe_http_get {url} {
    if {[catch {
        set token [::http::geturl $url -timeout 10000]
        set status [::http::status $token]
        
        if {$status eq "ok"} {
            set code [::http::ncode $token]
            if {$code == 200} {
                set result [::http::data $token]
            } else {
                set result "HTTP Error: $code"
            }
        } else {
            set result "Connection Error: $status"
        }
        
        ::http::cleanup $token
        return $result
        
    } error]} {
        return "Exception: $error"
    }
}

# Usage example
puts [safe_http_get "https://httpbin.org/status/200"]

Working with Headers

Custom headers can be added for authentication or content type specification:

#!/usr/bin/env tclsh
package require http

# Set custom headers
set headers [list "User-Agent" "MyApp/1.0" "Accept" "application/json"]

set token [::http::geturl "https://httpbin.org/headers" -headers $headers]
puts [::http::data $token]
::http::cleanup $token

Testing API Connectivity

When integrating with external APIs, it's important to verify connectivity and response formats. Here's a pattern for testing multiple endpoints:

#!/usr/bin/env tclsh
package require http

# API connectivity test function
proc test_api_endpoint {base_url endpoint_path} {
    set full_url "${base_url}${endpoint_path}"
    puts "Testing: $full_url"
    
    if {[catch {
        set token [::http::geturl $full_url -timeout 5000]
        set status [::http::status $token]
        set code [::http::ncode $token]
        
        puts "  Status: $status"
        puts "  HTTP Code: $code"
        
        ::http::cleanup $token
        
    } error]} {
        puts "  Error: $error"
    }
}

# Test common API endpoints
test_api_endpoint "https://httpbin.org" "/get"
test_api_endpoint "https://httpbin.org" "/status/200"
test_api_endpoint "https://httpbin.org" "/json"
Testing: https://httpbin.org/get Status: ok HTTP Code: 200 Testing: https://httpbin.org/status/200 Status: ok HTTP Code: 200 Testing: https://httpbin.org/json Status: ok HTTP Code: 200

Configuration Testing

For production deployments, it's useful to verify that your HTTP client configuration can reach required services. This pattern tests connectivity to common business APIs:

#!/usr/bin/env tclsh
package require http

# Configuration verification for business API endpoints
proc verify_business_connectivity {} {
    # Test connectivity to common business services
    set endpoints {
        "https://www.googleapis.com/gmail/v1/users/me/profile"
        "https://www.googleapis.com/calendar/v3/calendars/primary"
        "https://www.googleapis.com/drive/v3/about"
    }
    
    foreach endpoint $endpoints {
        puts "Verifying: $endpoint"
        
        if {[catch {
            set token [::http::geturl $endpoint -timeout 3000]
            set status [::http::status $token]
            set code [::http::ncode $token]
            
            if {$status eq "ok"} {
                puts "  Connectivity: OK"
                if {$code == 401} {
                    puts "  Authentication: Required (expected)"
                } else {
                    puts "  HTTP Response: $code"
                }
            } else {
                puts "  Connectivity: Failed ($status)"
            }
            
            ::http::cleanup $token
            
        } error]} {
            puts "  Error: $error"
        }
        puts ""
    }
}

verify_business_connectivity
Note: These connectivity tests will return 401 (Unauthorized) responses since no authentication credentials are provided. This is expected behavior and confirms that the endpoints are reachable.

Troubleshooting Common Issues

Connection Timeouts

If you're experiencing connection timeouts, try increasing the timeout value or testing with a simpler endpoint first:

# Test with longer timeout
set token [::http::geturl $url -timeout 30000]

SSL/TLS Issues

For HTTPS endpoints, ensure your Tcl installation includes TLS support:

package require tls
::http::register https 443 ::tls::socket

Authentication Testing

When working with authenticated APIs, you can test your credentials by making a simple authenticated request. For debugging purposes, some developers create test scripts that verify their tokens work correctly:

# Debug script for testing API authentication
# Note: Replace YOUR_TOKEN with actual token for testing
proc test_auth_token {service_url auth_token} {
    set headers [list "Authorization" "Bearer $auth_token"]
    
    if {[catch {
        set token [::http::geturl $service_url -headers $headers -timeout 5000]
        set status [::http::status $token]
        set code [::http::ncode $token]
        
        puts "Auth test for $service_url:"
        puts "  Status: $status, Code: $code"
        
        if {$code == 200} {
            puts "  Authentication: Valid"
        } elseif {$code == 401} {
            puts "  Authentication: Invalid token"
        } else {
            puts "  Response: [::http::data $token]"
        }
        
        ::http::cleanup $token
        
    } error]} {
        puts "  Error: $error"
    }
}

# Example usage (uncomment and provide real tokens for testing):
# test_auth_token "https://www.googleapis.com/gmail/v1/users/me/profile" "YOUR_GMAIL_TOKEN"
# test_auth_token "https://www.googleapis.com/calendar/v3/calendars/primary" "YOUR_CALENDAR_TOKEN"
Debugging Tip: When testing authentication, start with read-only endpoints like profile or about pages. These typically have minimal scope requirements and are safe for testing purposes.

HTTP Package Reference

Key procedures in the Tcl http package:

For complete documentation, see the official Tcl http package manual.

Additional Resources