Unlock Real-Time Weather Insights with Open Weather API

25 Apr 2025
Unlock Real-Time Weather Insights with Open Weather API

Open Weather API provides developers with powerful tools to access real-time weather data and forecasts globally. With its intuitive Cognitive Actions, you can easily integrate weather information into your applications, enhancing user experiences through accurate and timely data. Whether you’re building a travel app, a smart home system, or a weather dashboard, Open Weather simplifies the process of fetching essential weather information.

Imagine being able to provide users with current weather conditions for any city, or offering a detailed five-day forecast that updates every three hours. The API not only saves you development time but also ensures your application remains relevant and responsive to user needs.

Prerequisites

To get started with Open Weather, you will need an API key and a basic understanding of making API calls. This will allow you to authenticate your requests and retrieve the data you need.

Retrieve Current Weather by Coordinates

The "Retrieve Current Weather by Coordinates" action allows you to fetch real-time weather information based on latitude and longitude coordinates. This is particularly useful for applications that need to provide location-specific weather updates, like travel apps or outdoor activity planners.

Input Requirements

To use this action, you need to provide:

  • latitude: The latitude coordinate of the location (e.g., "30.438").
  • longitude: The longitude coordinate of the location (e.g., "-89.1028").

Expected Output

The response includes comprehensive weather data such as temperature, humidity, wind speed, and a description of the weather conditions, making it easy to display relevant information to users.

Use Cases for this specific action

  • Travel Applications: Provide travelers with current weather conditions at their destination.
  • Event Planning: Help users decide on outdoor events based on real-time weather updates.
  • Smart Home Systems: Integrate weather data to optimize heating or cooling systems based on current conditions.

```python
import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "1dd50caa-b27d-429a-9f41-5ea6841baa69" # Action ID for: Retrieve Current Weather by Coordinates

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "latitude": "30.438",
  "longitude": "-89.1028"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Retrieve 5-Day Weather Forecast
With the "Retrieve 5-Day Weather Forecast" action, you can access detailed weather forecasts updated every three hours. This feature is essential for applications that require advanced planning, such as agriculture apps or event management tools.

### Input Requirements
Similar to the current weather action, you will need:
- `latitude`: Latitude of the location.
- `longitude`: Longitude of the location.

### Expected Output
The output consists of forecast data for the next five days, including temperature ranges, precipitation chances, and wind conditions. This allows for a more comprehensive view of upcoming weather patterns.

### Use Cases for this specific action
- **Agricultural Apps**: Farmers can plan their activities based on the weather forecast.
- **Travel Itinerary Planning**: Users can adjust their travel plans based on expected weather conditions.
- **Outdoor Event Management**: Event organizers can make informed decisions about scheduling or rescheduling events.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "73173fd4-3555-42ba-9f1c-dcdfd4bcf0fc" # Action ID for: Retrieve 5-Day Weather Forecast

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "latitude": "30.438",
  "longitude": "-89.1028"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Fetch Current Weather by City
The "Fetch Current Weather by City" action enables you to retrieve real-time weather data for a specific city. This is particularly useful for applications that focus on urban areas or require user-friendly city-based searches.

### Input Requirements
To utilize this action, you must provide:
- `cityName`: The name of the city (e.g., "Landon").
- `language`: The language code for the response (e.g., "EN").

### Expected Output
You will receive current weather data, including temperature, humidity, wind speed, and a general weather description. This makes it easy to present localized weather information to your users.

### Use Cases for this specific action
- **City-Specific Weather Apps**: Users can get instant weather updates for their home city or any city they are interested in.
- **Travel Planning**: Travelers can check the current weather in cities they plan to visit.
- **Local News Apps**: News outlets can provide current weather updates relevant to their audience.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "aca2c45d-9378-4df3-b436-e7bb0ba5782a" # Action ID for: Fetch Current Weather by City

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "cityName": "landon",
  "language": "EN"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Conclusion
Open Weather API offers developers a robust solution for integrating real-time weather data into applications. By leveraging its Cognitive Actions, you can provide users with crucial weather information tailored to their needs. Whether it’s current conditions or detailed forecasts, the flexibility and ease of use make Open Weather an essential tool for any developer looking to enhance their application’s functionality. Start integrating these actions today and keep your users informed and engaged with timely weather updates!