Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OpenCage Geocoding API - Bash/Shell SDK

A robust, POSIX-compliant shell script SDK for the OpenCage Geocoding API. Perfect for DevOps automation, CI/CD pipelines, and system administration tasks.

Features

  • ✅ Forward Geocoding: Convert addresses to coordinates
  • ✅ Reverse Geocoding: Convert coordinates to addresses
  • ✅ Batch Processing: Process multiple addresses from files
  • ✅ Error Handling: Comprehensive HTTP and API error handling
  • ✅ Rate Limiting: Built-in request throttling
  • ✅ Logging: Configurable verbose logging with colors
  • ✅ POSIX Compliant: Works with bash, zsh, dash, and other shells
  • ✅ Dependencies: Only requires curl and jq (widely available)

Quick Start

Installation

# Download the SDK
curl -O https://raw.githubusercontent.com/geonot/opencage-bash-sdk/main/opencage.sh
chmod +x opencage.sh

# Or clone the repository  
git clone https://github.com/geonot/opencage-bash-sdk.git
cd opencage-bash-sdk

Get Your API Key

Sign up for a free API key at OpenCage Data.

Basic Usage

As a Script (CLI)

# Test connectivity
./opencage.sh ping

# Forward geocoding
./opencage.sh forward "Berlin, Germany"

# Reverse geocoding  
./opencage.sh reverse "52.520008,13.404954"

# Get coordinates only
./opencage.sh coords "1600 Amphitheatre Parkway, Mountain View, CA"

# Get address only
./opencage.sh address "37.422,-122.084"

As a Library (Source)

# Load functions into your shell
source opencage.sh

# Set your API key
export OPENCAGE_API_KEY="your-32-character-api-key-here"

# Use the functions
result=$(opencage_forward "London, UK")
echo "$result" | opencage_pretty_print

coordinates=$(opencage_get_coordinates "Paris, France")
echo "Paris coordinates: $coordinates"

Configuration

Environment Variables

Variable Default Description
OPENCAGE_API_KEY - Your OpenCage API key (required)
OPENCAGE_VERBOSE 0 Set to 1 for verbose logging
OPENCAGE_TIMEOUT 30 HTTP request timeout in seconds
OPENCAGE_DEFAULT_FORMAT json Default response format
OPENCAGE_DEFAULT_LANGUAGE en Default language for results
OPENCAGE_DEFAULT_LIMIT 10 Default number of results

Example Configuration

export OPENCAGE_API_KEY="your-api-key-here"
export OPENCAGE_VERBOSE=1
export OPENCAGE_TIMEOUT=60
source opencage.sh

API Functions

Core Functions

opencage_forward(address, [api_key], [limit], [language])

Convert an address to coordinates.

result=$(opencage_forward "New York City" "your-api-key" 5 "en")

opencage_reverse(coordinates, [api_key], [language])

Convert coordinates to an address.

result=$(opencage_reverse "40.7589,-73.9851" "your-api-key" "en")

Advanced Functions with Full Parameter Support

opencage_forward_advanced(query, [api_key], [option=value...])

Forward geocoding with comprehensive OpenCage API parameter support.

Supported Parameters:

  • limit=N - Maximum number of results
  • language=LANG - Language for results
  • countrycode=CC - Restrict to country codes (comma-separated)
  • bounds=BOUNDS - Restrict to bounding box (minlat,minlng,maxlat,maxlng)
  • proximity=LAT,LNG - Bias results towards coordinates
  • abbrv=1 - Use abbreviated address format
  • min_confidence=N - Minimum confidence level (1-10)
  • no_annotations=1 - Skip annotations
  • no_dedupe=1 - Skip deduplication
  • no_record=1 - Skip recording query
  • roadinfo=1 - Include road information
  • add_request=1 - Include request details in response
# Basic usage
opencage_forward_advanced "London" "$API_KEY" countrycode=gb limit=5

# Multiple parameters
opencage_forward_advanced "Paris" "$API_KEY" bounds=48,2,49,3 abbrv=1 language=fr

# Complex query
opencage_forward_advanced "coffee shop" "$API_KEY" proximity=40.7589,-73.9851 countrycode=us min_confidence=5

opencage_reverse_advanced(coordinates, [api_key], [option=value...])

Reverse geocoding with comprehensive OpenCage API parameter support.

Supported Parameters:

  • language=LANG - Language for results
  • abbrv=1 - Use abbreviated address format
  • no_annotations=1 - Skip annotations
  • no_record=1 - Skip recording query
  • roadinfo=1 - Include road information
  • add_request=1 - Include request details in response
# Basic usage
opencage_reverse_advanced "52.520008,13.404954" "$API_KEY" language=de abbrv=1

# With multiple options
opencage_reverse_advanced "40.7589,-73.9851" "$API_KEY" roadinfo=1 add_request=1

Convenience Functions

opencage_get_coordinates(address, [api_key])

Get just the coordinates for an address.

coords=$(opencage_get_coordinates "Tokyo, Japan")
echo "Tokyo is at: $coords"
# Output: Tokyo is at: 35.6762,139.6503

opencage_get_address(coordinates, [api_key])

Get just the formatted address for coordinates.

address=$(opencage_get_address "48.8566,2.3522")
echo "Address: $address"
# Output: Address: Paris, France

Batch Processing

opencage_batch_forward(input_file, [api_key], [output_file])

Process multiple addresses from a file.

# Create input file
echo -e "Berlin, Germany\nTokyo, Japan\nNew York, USA" > addresses.txt

# Batch geocode
opencage_batch_forward addresses.txt your-api-key results.txt

Utility Functions

opencage_ping()

Test API connectivity.

if opencage_ping; then
    echo "API is reachable"
fi

opencage_extract_coordinates(json_response)

Extract coordinates from API response.

result=$(opencage_forward "London")
coords=$(opencage_extract_coordinates "$result")

opencage_pretty_print(json_response)

Pretty print JSON response.

result=$(opencage_forward "London")
opencage_pretty_print "$result"

Examples

DevOps Integration

#!/bin/bash
source opencage.sh

# Geocode server locations from configuration
while read -r server_address; do
    coordinates=$(opencage_get_coordinates "$server_address")
    if [[ $? -eq 0 ]]; then
        echo "Server at $server_address is located at: $coordinates"
        # Add to monitoring system, etc.
    else
        echo "Failed to geocode: $server_address"
    fi
done < server_locations.txt

CI/CD Pipeline

#!/bin/bash
# Deploy script with location validation
source opencage.sh

DEPLOYMENT_ADDRESS="1600 Amphitheatre Parkway, Mountain View, CA"
REQUIRED_COORDINATES="37.4220,-122.0841"

actual_coords=$(opencage_get_coordinates "$DEPLOYMENT_ADDRESS")
if [[ "$actual_coords" == "$REQUIRED_COORDINATES" ]]; then
    echo "✅ Deployment location verified"
    # Continue deployment
else
    echo "❌ Location mismatch: expected $REQUIRED_COORDINATES, got $actual_coords"
    exit 1
fi

Log Processing

#!/bin/bash
source opencage.sh

# Process access logs with IP geolocation
while read -r log_line; do
    ip=$(echo "$log_line" | cut -d' ' -f1)
    # Use IP geolocation service to get coordinates, then reverse geocode
    location=$(opencage_get_address "$coordinates")
    echo "$log_line | Location: $location"
done < access.log

Error Handling

The SDK provides comprehensive error handling for common scenarios:

  • Network Issues: Connection timeouts, DNS failures
  • API Errors: Invalid API key, quota exceeded, rate limiting
  • Data Issues: Invalid coordinates, no results found
  • Input Validation: Malformed addresses, missing parameters

All errors are logged with appropriate severity levels and return non-zero exit codes.

if ! opencage_forward "Invalid Address"; then
    echo "Geocoding failed"
    # Handle error appropriately
fi

Dependencies

The SDK requires only two common utilities:

  • curl: For HTTP requests (usually pre-installed)
  • jq: For JSON parsing

Installation

# Ubuntu/Debian
sudo apt-get install curl jq

# CentOS/RHEL
sudo yum install curl jq

# macOS  
brew install curl jq

# Alpine Linux
apk add curl jq

Rate Limiting

The OpenCage API has rate limits. The SDK includes built-in throttling for batch operations:

  • Batch processing automatically adds 100ms delays between requests
  • Monitor your usage in the OpenCage Dashboard
  • Consider caching results for repeated queries

Testing

Run the test suite:

./test.sh

The test suite requires:

  • Valid OpenCage API key set in OPENCAGE_API_KEY
  • Internet connectivity
  • All dependencies installed

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

License

MIT License

Copyright (c) 2025 Rome Stone

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Support


About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages