# Recipe: 5-Day Daily Forecast

import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "zudoku/ui/Accordion";

export const StepHeader = ({ n, children }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: "0.75rem" }}>
    <span style={{
      display: "inline-flex",
      alignItems: "center",
      justifyContent: "center",
      width: "1.75rem",
      height: "1.75rem",
      minWidth: "1.75rem",
      borderRadius: "9999px",
      backgroundColor: "#F05514",
      color: "#FFFFFF",
      fontSize: "0.875rem",
      fontWeight: 600,
      flexShrink: 0,
      lineHeight: 1,
    }}>
      {n}
    </span>
    <span>{children}</span>
  </span>
);

This recipe shows how to retrieve a 5-day daily forecast — the most common weather data type for travel apps, event planners, home screens, and marketing dashboards.

:::note
**These recipes are teaching examples — not production code.**

- **Host:** examples use the development host **apidev.accuweather.com**. Switch to **api.accuweather.com** for production.
- **Production hardening:** GZIP compression, caching, retries with exponential backoff, and error handling are not included. See the [Best Practices](/developers/best-practices) guide.
:::

## Scenario

> "I want to display a 5-day forecast card showing the daily high/low temperatures and whether to expect rain for each day."

:::note

You'll need a **LocationKey** before starting. If you don't have one, follow the [Location Search recipe](/recipes/location-search) first.
For this example we use LocationKey `349727` (New York City).

:::

---

<Accordion type="multiple" defaultValue={["step-1"]} className="my-6">

<AccordionItem value="step-1">
  <AccordionTrigger><StepHeader n={1}>Choose a forecast duration</StepHeader></AccordionTrigger>
  <AccordionContent>

The Daily Forecast API supports multiple durations:

| Duration param | Days of data | Notes |
|----------------|-------------|-------|
| `1day` | 1 | Today only |
| `5day` | 5 | Most common; free-tier compatible |
| `10day` | 10 | Medium-range planning |
| `15day` | 15 | Extended planning |
| `25day` | 25 | Seasonal planning |
| `45day` | 45 | Requires Enterprise tier |

  </AccordionContent>
</AccordionItem>

<AccordionItem value="step-2">
  <AccordionTrigger><StepHeader n={2}>Make the request</StepHeader></AccordionTrigger>
  <AccordionContent>

**Endpoint pattern:**
```
GET https://apidev.accuweather.com/forecasts/v1/daily/{duration}/{locationKey}.json?apikey={YOUR_API_KEY}
```

<CodeTabs syncKey="language">

```ts title="TypeScript"
const apiKey = "{YOUR_API_KEY}";
const locationKey = "349727";
const duration = "5day";

const response = await fetch(
  `https://apidev.accuweather.com/forecasts/v1/daily/${duration}/${locationKey}.json?apikey=${apiKey}`
);
const forecast: Record<string, any> = await response.json();
// forecast.Headline — most significant event over the period
// forecast.DailyForecasts — array of daily forecast objects
```

```python title="Python"
import requests

api_key = "{YOUR_API_KEY}"
location_key = "349727"
duration = "5day"

response = requests.get(
    f"https://apidev.accuweather.com/forecasts/v1/daily/{duration}/{location_key}.json",
    params={"apikey": api_key},
)
forecast = response.json()
headline = forecast["Headline"]
daily = forecast["DailyForecasts"]
```

```csharp title="C#"
using var client = new HttpClient();

var apiKey = "{YOUR_API_KEY}";
var locationKey = "349727";
var duration = "5day";
var url = $"https://apidev.accuweather.com/forecasts/v1/daily/{duration}/{locationKey}.json?apikey={apiKey}";
var response = await client.GetAsync(url);
var data = await response.Content.ReadAsStringAsync();
```

```java title="Java"
HttpClient client = HttpClient.newHttpClient();
String apiKey = "{YOUR_API_KEY}";
String locationKey = "349727";
String duration = "5day";
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://apidev.accuweather.com/forecasts/v1/daily/"
        + duration + "/" + locationKey + ".json?apikey=" + apiKey))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String data = response.body();
```

```bash title="bash"
curl "https://apidev.accuweather.com/forecasts/v1/daily/5day/349727.json?apikey={YOUR_API_KEY}"
```

</CodeTabs>

  </AccordionContent>
</AccordionItem>

<AccordionItem value="step-3">
  <AccordionTrigger><StepHeader n={3}>Inspect the response</StepHeader></AccordionTrigger>
  <AccordionContent>

The response has two top-level keys: `Headline` (the most notable weather event for the period) and `DailyForecasts` (the per-day array).

```json
{
  "Headline": {
    "EffectiveDate": "2024-06-16T08:00:00-04:00",
    "Severity": 3,
    "Text": "Expect rainy weather Sunday morning",
    "Category": "rain",
    "EndDate": "2024-06-16T14:00:00-04:00"
  },
  "DailyForecasts": [
    {
      "Date": "2024-06-15T07:00:00-04:00",
      "EpochDate": 1718445600,
      "Temperature": {
        "Minimum": { "Value": 65, "Unit": "F", "UnitType": 18 },
        "Maximum": { "Value": 82, "Unit": "F", "UnitType": 18 }
      },
      "Day": {
        "Icon": 3,
        "IconPhrase": "Partly sunny",
        "HasPrecipitation": false
      },
      "Night": {
        "Icon": 35,
        "IconPhrase": "Partly cloudy",
        "HasPrecipitation": false
      }
    },
    {
      "Date": "2024-06-16T07:00:00-04:00",
      "EpochDate": 1718532000,
      "Temperature": {
        "Minimum": { "Value": 60, "Unit": "F", "UnitType": 18 },
        "Maximum": { "Value": 71, "Unit": "F", "UnitType": 18 }
      },
      "Day": {
        "Icon": 18,
        "IconPhrase": "Rain",
        "HasPrecipitation": true,
        "PrecipitationType": "Rain",
        "PrecipitationIntensity": "Moderate"
      },
      "Night": {
        "Icon": 34,
        "IconPhrase": "Mostly clear",
        "HasPrecipitation": false
      }
    }
  ]
}
```

  </AccordionContent>
</AccordionItem>

<AccordionItem value="step-4">
  <AccordionTrigger><StepHeader n={4}>Render a 5-day forecast card</StepHeader></AccordionTrigger>
  <AccordionContent>

<CodeTabs syncKey="language">

```ts title="TypeScript"
const { Headline, DailyForecasts } = forecast;

console.log(`⚠ Headline: ${Headline.Text}\n`);

DailyForecasts.forEach((day: any) => {
  const date = new Date(day.Date).toLocaleDateString("en-US", {
    weekday: "short", month: "short", day: "numeric",
  });
  const hi = day.Temperature.Maximum.Value;
  const lo = day.Temperature.Minimum.Value;
  const dayPhrase = day.Day.IconPhrase;
  const rain = day.Day.HasPrecipitation
    ? `🌧 ${day.Day.PrecipitationType}`
    : "No rain";

  console.log(`${date}: High ${hi}°F / Low ${lo}°F | ${dayPhrase} | ${rain}`);
});
```

```python title="Python"
from datetime import datetime

print(f"⚠ Headline: {headline['Text']}\n")

for day in daily:
    date = datetime.fromisoformat(day["Date"]).strftime("%a, %b %-d")
    hi = day["Temperature"]["Maximum"]["Value"]
    lo = day["Temperature"]["Minimum"]["Value"]
    phrase = day["Day"]["IconPhrase"]
    rain = f"🌧 {day['Day']['PrecipitationType']}" if day["Day"]["HasPrecipitation"] else "No rain"
    print(f"{date}: High {hi}°F / Low {lo}°F | {phrase} | {rain}")
```

```csharp title="C#"
using System.Text.Json;

var doc = JsonDocument.Parse(data);
var headline = doc.RootElement.GetProperty("Headline").GetProperty("Text").GetString();
var dailyForecasts = doc.RootElement.GetProperty("DailyForecasts");

Console.WriteLine($"⚠ Headline: {headline}\n");

foreach (var day in dailyForecasts.EnumerateArray())
{
    var date = DateTime.Parse(day.GetProperty("Date").GetString()!).ToString("ddd, MMM d");
    var hi = day.GetProperty("Temperature").GetProperty("Maximum").GetProperty("Value").GetDouble();
    var lo = day.GetProperty("Temperature").GetProperty("Minimum").GetProperty("Value").GetDouble();
    var phrase = day.GetProperty("Day").GetProperty("IconPhrase").GetString();
    var hasPrecip = day.GetProperty("Day").GetProperty("HasPrecipitation").GetBoolean();
    var rain = hasPrecip
        ? $"🌧 {day.GetProperty("Day").GetProperty("PrecipitationType").GetString()}"
        : "No rain";

    Console.WriteLine($"{date}: High {hi}°F / Low {lo}°F | {phrase} | {rain}");
}
```

```java title="Java"
import org.json.JSONObject;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

var doc = new JSONObject(data);
var headlineText = doc.getJSONObject("Headline").getString("Text");
var dailyForecasts = doc.getJSONArray("DailyForecasts");
var fmt = DateTimeFormatter.ofPattern("EEE, MMM d");

System.out.println("⚠ Headline: " + headlineText + "\n");

for (int i = 0; i < dailyForecasts.length(); i++) {
    var day = dailyForecasts.getJSONObject(i);
    var date = OffsetDateTime.parse(day.getString("Date")).format(fmt);
    var hi = day.getJSONObject("Temperature").getJSONObject("Maximum").getDouble("Value");
    var lo = day.getJSONObject("Temperature").getJSONObject("Minimum").getDouble("Value");
    var dayInfo = day.getJSONObject("Day");
    var phrase = dayInfo.getString("IconPhrase");
    var rain = dayInfo.getBoolean("HasPrecipitation")
        ? "🌧 " + dayInfo.getString("PrecipitationType")
        : "No rain";

    System.out.println(date + ": High " + hi + "°F / Low " + lo + "°F | " + phrase + " | " + rain);
}
```

```bash title="bash"
echo "$DATA" | jq -r '"⚠ Headline: \(.Headline.Text)\n"'
echo "$DATA" | jq -r '.DailyForecasts[] |
  "\(.Date[0:10])  High \(.Temperature.Maximum.Value)°F / Low \(.Temperature.Minimum.Value)°F  |  \(.Day.IconPhrase)  |  " +
  (if .Day.HasPrecipitation then "🌧 \(.Day.PrecipitationType)" else "No rain" end)'
```

</CodeTabs>

Output:
```
⚠ Headline: Expect rainy weather Sunday morning

Sat, Jun 15: High 82°F / Low 65°F | Partly sunny | No rain
Sun, Jun 16: High 71°F / Low 60°F | Rain | 🌧 Rain
```

  </AccordionContent>
</AccordionItem>

</Accordion>

---

## Extended details

Add `details=true` to receive additional fields per day: sunrise/sunset, moon phase, air quality & pollen indices, precipitation probability, wind, cloud cover, and more.

```bash
curl "https://apidev.accuweather.com/forecasts/v1/daily/5day/349727.json?apikey={YOUR_API_KEY}&details=true"
```

Selected additional fields with `details=true`:

```json
{
  "Sun": {
    "Rise": "2024-06-15T05:27:00-04:00",
    "Set": "2024-06-15T20:29:00-04:00"
  },
  "Moon": {
    "Phase": "WaxingCrescent",
    "Age": 8
  },
  "HoursOfSun": 7.2,
  "AirAndPollen": [
    { "Name": "AirQuality", "Value": 38, "Category": "Good", "CategoryValue": 1 },
    { "Name": "Grass", "Value": 3, "Category": "Low", "CategoryValue": 1 },
    { "Name": "UVIndex", "Value": 8, "Category": "Very High", "CategoryValue": 4 }
  ],
  "Day": {
    "PrecipitationProbability": 20,
    "ThunderstormProbability": 5,
    "Wind": {
      "Speed": { "Value": 10.4, "Unit": "mi/h", "UnitType": 9 },
      "Direction": { "Degrees": 210, "Localized": "SSW", "English": "SSW" }
    },
    "CloudCover": 38,
    "ShortPhrase": "Some sun, pleasant",
    "LongPhrase": "Some sun, pleasant and not as humid"
  }
}
```

:::tip
`AirAndPollen` is perfect for building health-aware weather features — surface pollen, air quality, and UV index alongside the standard forecast data.
:::

---

## Key response fields

| Field | Type | Description |
|-------|------|-------------|
| `Headline.Text` | String | Plain-language summary of the most significant event |
| `Headline.Severity` | Integer | Severity level (1 = extreme → 7 = minor) |
| `DailyForecasts[].Date` | String | ISO 8601 date for the forecast day |
| `DailyForecasts[].Temperature.Minimum.Value` | Number | Daily low temperature |
| `DailyForecasts[].Temperature.Maximum.Value` | Number | Daily high temperature |
| `DailyForecasts[].Day.Icon` | Integer | Daytime weather icon code |
| `DailyForecasts[].Day.IconPhrase` | String | Daytime weather description |
| `DailyForecasts[].Day.HasPrecipitation` | Boolean | Whether daytime precipitation is expected |
| `DailyForecasts[].Day.PrecipitationType` | String \| null | `"Rain"`, `"Snow"`, `"Ice"`, or `"Mixed"` |
| `DailyForecasts[].Night.IconPhrase` | String | Nighttime weather description |
| `DailyForecasts[].Day.ShortPhrase` *(details)* | String | Short daytime summary phrase |
| `DailyForecasts[].Day.PrecipitationProbability` *(details)* | Integer | Probability of any daytime precipitation |
| `DailyForecasts[].Sun` *(details)* | Object | Sunrise and sunset times |
| `DailyForecasts[].AirAndPollen` *(details)* | Array | Pollen, UV, and air quality indices |

---

## Request metric units

Append `&metric=true` to receive temperatures in Celsius instead of Fahrenheit:

```bash
curl "https://apidev.accuweather.com/forecasts/v1/daily/5day/349727.json?apikey={YOUR_API_KEY}&metric=true"
```

---

## Common pitfalls

:::warning

**Headline vs. per-day data** — The `Headline` describes the *single most significant* event across the entire forecast period, not just today. Don't use it as a substitute for per-day data; always read `DailyForecasts` for day-by-day accuracy.

:::

:::note

**`HasPrecipitation` vs. `PrecipitationProbability`** — `HasPrecipitation` (in the basic response) is a boolean threshold. For a nuanced view, use `details=true` to get the actual `PrecipitationProbability` percentage so you can tune your display (e.g., show a rain icon only above 40%).

:::

---

## Complete code sample

Copy a full, runnable example that fetches the 5-day forecast and prints a day-by-day summary.

<CodeTabs syncKey="language">

```ts title="TypeScript"
const API_KEY = "{YOUR_API_KEY}";
const locationKey = "349727";

// Step 1: Fetch the 5-day forecast
const res = await fetch(
  `https://apidev.accuweather.com/forecasts/v1/daily/5day/${locationKey}.json?apikey=${API_KEY}`
);
const data: Record<string, any> = await res.json();

console.log("\n📅 5-Day Forecast");
console.log("━".repeat(42) + "\n");

// Step 2: Print the headline
console.log(`⚠ Headline: ${data.Headline.Text}\n`);

// Step 3: Daily summary
for (const day of data.DailyForecasts) {
  const date = new Date(day.Date).toLocaleDateString("en-US", {
    weekday: "short",
    month: "short",
    day: "numeric",
  });
  const hi = day.Temperature.Maximum.Value;
  const lo = day.Temperature.Minimum.Value;
  const phrase = day.Day.IconPhrase;
  const rain = day.Day.HasPrecipitation
    ? `🌧 ${day.Day.PrecipitationType}`
    : "No rain";

  console.log(`${date}: High ${hi}°F / Low ${lo}°F | ${phrase} | ${rain}`);
}
```

```python title="Python"
from datetime import datetime
import requests

API_KEY = "{YOUR_API_KEY}"
location_key = "349727"

# Step 1: Fetch the 5-day forecast
resp = requests.get(
    f"https://apidev.accuweather.com/forecasts/v1/daily/5day/{location_key}.json",
    params={"apikey": API_KEY},
)
data = resp.json()

print("\n📅 5-Day Forecast")
print("━" * 42 + "\n")

# Step 2: Print the headline
print(f"⚠ Headline: {data['Headline']['Text']}\n")

# Step 3: Daily summary
for day in data["DailyForecasts"]:
    date = datetime.fromisoformat(day["Date"]).strftime("%a, %b %-d")
    hi = day["Temperature"]["Maximum"]["Value"]
    lo = day["Temperature"]["Minimum"]["Value"]
    phrase = day["Day"]["IconPhrase"]
    rain = (
        f"🌧 {day['Day']['PrecipitationType']}"
        if day["Day"]["HasPrecipitation"]
        else "No rain"
    )
    print(f"{date}: High {hi}°F / Low {lo}°F | {phrase} | {rain}")
```

```csharp title="C#"
using System.Text.Json;

var apiKey = "{YOUR_API_KEY}";
var locationKey = "349727";

// Step 1: Fetch the 5-day forecast
using var client = new HttpClient();
var response = await client.GetStringAsync(
    $"https://apidev.accuweather.com/forecasts/v1/daily/5day/{locationKey}.json?apikey={apiKey}");

using var doc = JsonDocument.Parse(response);

Console.WriteLine("\n📅 5-Day Forecast");
Console.WriteLine(new string('━', 42) + "\n");

// Step 2: Print the headline
var headline = doc.RootElement.GetProperty("Headline").GetProperty("Text").GetString();
Console.WriteLine($"⚠ Headline: {headline}\n");

// Step 3: Daily summary
foreach (var day in doc.RootElement.GetProperty("DailyForecasts").EnumerateArray())
{
    var date = DateTime.Parse(day.GetProperty("Date").GetString()!).ToString("ddd, MMM d");
    var hi = day.GetProperty("Temperature").GetProperty("Maximum").GetProperty("Value").GetDouble();
    var lo = day.GetProperty("Temperature").GetProperty("Minimum").GetProperty("Value").GetDouble();
    var dayPart = day.GetProperty("Day");
    var phrase = dayPart.GetProperty("IconPhrase").GetString();
    var rain = dayPart.GetProperty("HasPrecipitation").GetBoolean()
        ? $"🌧 {dayPart.GetProperty("PrecipitationType").GetString()}"
        : "No rain";

    Console.WriteLine($"{date}: High {hi}°F / Low {lo}°F | {phrase} | {rain}");
}
```

```java title="Java"
import org.json.JSONObject;
import org.json.JSONArray;
import java.net.URI;
import java.net.http.*;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class DailyForecast {
    public static void main(String[] args) throws Exception {
        String apiKey = "{YOUR_API_KEY}";
        String locationKey = "349727";

        // Step 1: Fetch the 5-day forecast
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(
                "https://apidev.accuweather.com/forecasts/v1/daily/5day/"
                + locationKey + ".json?apikey=" + apiKey))
            .build();

        HttpResponse<String> response =
            client.send(request, HttpResponse.BodyHandlers.ofString());

        var doc = new JSONObject(response.body());
        var fmt = DateTimeFormatter.ofPattern("EEE, MMM d");

        System.out.println("\n📅 5-Day Forecast");
        System.out.println("━".repeat(42) + "\n");

        // Step 2: Print the headline
        var headline = doc.getJSONObject("Headline").getString("Text");
        System.out.println("⚠ Headline: " + headline + "\n");

        // Step 3: Daily summary
        var dailyForecasts = doc.getJSONArray("DailyForecasts");
        for (int i = 0; i < dailyForecasts.length(); i++) {
            var day = dailyForecasts.getJSONObject(i);
            var date = OffsetDateTime.parse(day.getString("Date")).format(fmt);
            var temp = day.getJSONObject("Temperature");
            var hi = temp.getJSONObject("Maximum").getDouble("Value");
            var lo = temp.getJSONObject("Minimum").getDouble("Value");
            var dayPart = day.getJSONObject("Day");
            var phrase = dayPart.getString("IconPhrase");
            var rain = dayPart.getBoolean("HasPrecipitation")
                ? "🌧 " + dayPart.getString("PrecipitationType")
                : "No rain";

            System.out.printf("%s: High %.0f°F / Low %.0f°F | %s | %s%n",
                date, hi, lo, phrase, rain);
        }
    }
}
```

```bash title="bash"
#!/bin/bash
API_KEY="{YOUR_API_KEY}"
LOCATION_KEY="349727"

# Step 1: Fetch the 5-day forecast
DATA=$(curl -s "https://apidev.accuweather.com/forecasts/v1/daily/5day/${LOCATION_KEY}.json?apikey=${API_KEY}")

echo ""
echo "📅 5-Day Forecast"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Step 2: Print the headline
HEADLINE=$(echo "$DATA" | jq -r '.Headline.Text')
echo "⚠ Headline: ${HEADLINE}"
echo ""

# Step 3: Daily summary
echo "$DATA" | jq -r '.DailyForecasts[] |
  "\(.Date[0:10])  High \(.Temperature.Maximum.Value)°F / Low \(.Temperature.Minimum.Value)°F  |  \(.Day.IconPhrase)  |  " +
  (if .Day.HasPrecipitation then "🌧 \(.Day.PrecipitationType)" else "No rain" end)'
```

</CodeTabs>

---

## Next steps

- [Hourly Forecast](/recipes/hourly-forecast) — drill down into hour-by-hour data for any of these days
- [Current Conditions](/recipes/current-conditions) — pair forecasts with a live snapshot of what's happening right now
