{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# APIs and Python's Requests Library"
      ],
      "metadata": {
        "id": "SFjgZAyFuSUZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# imports necessary for this notebook\n",
        "\n",
        "import requests\n",
        "import pandas as pd"
      ],
      "metadata": {
        "id": "2L8gIA95uRfV"
      },
      "execution_count": 21,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## What is an API?\n",
        "\n",
        "API stands for Application Programming Interface. It's a set of rules and tools that allows different software applications to communicate with each other. Think of it as a waiter in a restaurant who takes your order (the request) and brings your food (the response) from the kitchen (the server).\n",
        "\n",
        "## What is an API Used For?\n",
        "APIs are used for a variety of tasks, such as:\n",
        "\n",
        "* Accessing Web Services: Websites often provide APIs to allow other applications to use their data and services. For example, a weather app might use a weather service's API to get current weather information.\n",
        "\n",
        "* Integrating Different Systems: Businesses use APIs to connect different systems and allow them to work together. For example, an online store might use a payment gateway API to process payments.\n",
        "\n",
        "* Automating Tasks: APIs can be used to automate tasks. For instance, a social media management tool might use APIs to schedule posts automatically.\n",
        "\n",
        "## How HTTP is Used to Contact APIs\n",
        "* Most APIs, especially web-based ones, use HTTP (Hypertext Transfer Protocol) to communicate. HTTP is the protocol that web browsers use to load web pages, but it's also perfect for sending requests to APIs and receiving responses. Here's how it typically works:\n",
        "\n",
        "### Making a Request\n",
        "\n",
        "To use an API, you send an HTTP request to a specific URL (the API endpoint). This request usually includes:\n",
        "\n",
        "* Method: The type of request you're making. Common methods are:\n",
        "* * GET (to retrieve data)\n",
        "* * POST (to send data)\n",
        "* * PUT (to update data)\n",
        "* * DELETE (to remove data).\n",
        "\n",
        "* Headers: Additional information like authentication details.\n",
        "* Body: (for some methods) - Data you're sending to the API.\n",
        "\n",
        "### Common HTTP Status Codes:\n",
        "\n",
        "Each response will have a status code associated with it, which describes the success or failure of the request in a way that can help us with debugging.\n",
        "\n",
        "* 200 OK: The request was successful.\n",
        "* 201 Created: The request was successful and a resource was created.\n",
        "* 204 No Content: The request was successful but there is no content to return.\n",
        "* 400 Bad Request: The request was malformed or invalid.\n",
        "* 401 Unauthorized: Authentication is required and has failed or has not yet been provided.\n",
        "* 403 Forbidden: The request was valid, but the server is refusing action.\n",
        "* 404 Not Found: The requested resource could not be found.\n",
        "* 500 Internal Server Error: The server encountered an unexpected condition.\n",
        "* 502 Bad Gateway: The server was acting as a gateway or proxy and received an invalid response from the upstream server.\n",
        "* 503 Service Unavailable: The server is currently unable to handle the request due to temporary overloading or maintenance.\n",
        "\n",
        "### Getting a Response:\n",
        "\n",
        "* The API processes your request and sends back an HTTP response. This response includes:\n",
        "* * Status Code: Indicates if the request was successful (e.g., 200 OK) or if there was an error (e.g., 404 Not Found).\n",
        "* * Headers: Metadata about the response.\n",
        "* * Body: The actual data you requested, usually in a format like JSON (JavaScript Object Notation).\n",
        "\n",
        "## What is the Python Requests Library?\n",
        "\n",
        "The Python requests library is a simple and user-friendly library for making HTTP requests. It allows you to send HTTP requests to interact with APIs, just like a web browser but from within your Python code."
      ],
      "metadata": {
        "id": "QU87SKUluRMT"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Anatomy of an API\n",
        "\n",
        "An API (Application Programming Interface) provides a way for different software applications to communicate. Here are the main components of an API:\n",
        "\n",
        "1. Endpoints\n",
        "Endpoints are specific URLs where the API can be accessed. Each endpoint corresponds to a specific function or resource in the API. For example:\n",
        "\n",
        "* https://api.example.com/users might retrieve user information.\n",
        "* https://api.example.com/documents/123 might retrieve a document with the specific ID '123'\n",
        "\n",
        "Endpoints often require you to include parameters (see below!) in the URL path or query string to specify what data you want to access.\n",
        "\n",
        "2. API Keys and Authentication\n",
        "API keys are used to authenticate and authorize access to the API. They ensure that only authorized users can access the API and help track usage.\n",
        "\n",
        "* API Key: A unique identifier that you include in your request to authenticate it. This is like a password that stays the same.\n",
        "* OAuth Tokens: More secure tokens used for authentication. These tokens are often included in the request headers. These are like one-time-passcodes that change with every request."
      ],
      "metadata": {
        "id": "KtQ-lCCevIFM"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## OpenWeatherMap API\n",
        "\n",
        "https://openweathermap.org\n",
        "\n",
        "OpenWeatherMap API allows users to access current weather data, forecasts, and historical weather data. The free tier provides a good range of features, suitable for many applications.\n",
        "\n",
        "Key Features of the Free OpenWeatherMap API\n",
        "Current Weather Data: Get current weather information for a specific location, including temperature, humidity, wind speed, and weather conditions.\n",
        "\n",
        "5-Day Weather Forecast: Retrieve weather forecasts for the next five days, including data for different times of the day.\n",
        "\n",
        "Weather Alerts: Receive severe weather alerts for specific regions.\n",
        "\n",
        "Air Pollution Data: Access air pollution data for specific locations, including various pollutants' levels.\n",
        "\n",
        "Instructions:\n",
        "1. Sign up for a free account.\n",
        "2. Get your API key by licking on your account and selecting 'my API key'"
      ],
      "metadata": {
        "id": "H7dFSLwQxj7s"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Making Your First Request\n",
        "\n",
        "You will need a few things to make a request:\n",
        "\n",
        "1. Endpoint\n",
        "2. Key\n",
        "3. Parameters"
      ],
      "metadata": {
        "id": "aJSWC3Bnvf-G"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# This is the 'endpoint' we will 'call' to get data from the API.\n",
        "# You will fine loads of info about how to use APIs in the API documentation.\n",
        "\n",
        "owm_endpoint = \"http://api.openweathermap.org/data/2.5/weather\""
      ],
      "metadata": {
        "id": "A18LnsRHxjQs"
      },
      "execution_count": 22,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 23,
      "metadata": {
        "id": "263R4oXeuxJN"
      },
      "outputs": [],
      "source": [
        "# Please don't use my key as you might spam my account and cause it to be closed! Thanks :D\n",
        "\n",
        "owm_api_key = \"cd30189c3ebf97e39e3a734e6ffb2534\""
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Parameters for the API request\n",
        "params = {\n",
        "    'q': 'Marrakesh',              # City name\n",
        "    'appid': owm_api_key,       # Your API key\n",
        "    'units': 'metric'           # Units of measurement (metric, imperial, or standard)\n",
        "}\n"
      ],
      "metadata": {
        "id": "f7TJgqEE1R3g"
      },
      "execution_count": 24,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Make the GET request\n",
        "\n",
        "Use the requests.get() method to make the GET request to the OpenWeatherMap API. Pass the URL and the parameters to this method.\n",
        "\n",
        "The variable 'response' (though remember - you can ame it whateevr you like!) stores the results of the API request."
      ],
      "metadata": {
        "id": "olG4mrk61yH7"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Make the GET request\n",
        "response = requests.get(owm_endpoint, params=params)"
      ],
      "metadata": {
        "id": "Vb0NQIyW1xvy"
      },
      "execution_count": 25,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Check the response status code\n",
        "It's important to check the status code of the response to ensure the request was successful. A status code of 200 indicates success."
      ],
      "metadata": {
        "id": "iLuG1wq21_gd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Check if the request was successful\n",
        "if response.status_code == 200:\n",
        "    # If successful, parse the JSON response\n",
        "    data = response.json()\n",
        "    print(data)\n",
        "else:\n",
        "    # If not successful, print the error code\n",
        "    print(f\"Error: {response.status_code}\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Vj9Bdr4C192u",
        "outputId": "ac464163-4860-4e07-c05c-2efc11876228"
      },
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'coord': {'lon': -8.0083, 'lat': 31.6315}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': 'scattered clouds', 'icon': '03d'}], 'base': 'stations', 'main': {'temp': 27.04, 'feels_like': 27.1, 'temp_min': 27.04, 'temp_max': 32.42, 'pressure': 1010, 'humidity': 44, 'sea_level': 1010, 'grnd_level': 956}, 'visibility': 10000, 'wind': {'speed': 1.54, 'deg': 30}, 'clouds': {'all': 40}, 'dt': 1725526824, 'sys': {'type': 1, 'id': 2409, 'country': 'MA', 'sunrise': 1725516626, 'sunset': 1725562274}, 'timezone': 3600, 'id': 2542997, 'name': 'Marrakesh', 'cod': 200}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Output JSON:\n",
        "\n",
        "```\n",
        "{'coord':\n",
        "    {'lon': -0.1257,\n",
        "    'lat': 51.5085},\n",
        "'weather':\n",
        "      [\n",
        "      {'id': 801,\n",
        "      'main': 'Clouds',\n",
        "      'description': 'few clouds',\n",
        "      'icon': '02d'}\n",
        "      ],\n",
        "'base': 'stations',\n",
        "'main':\n",
        "    {'temp': 14.05,\n",
        "    'feels_like': 13.63,\n",
        "    'temp_min': 12.49,\n",
        "    'temp_max': 15.2,\n",
        "    'pressure': 1012,\n",
        "    'humidity': 81},\n",
        "'visibility': 10000,\n",
        "'wind':\n",
        "    {'speed': 4.63,\n",
        "    'deg': 330},\n",
        "'clouds':\n",
        "    {'all': 20},\n",
        "'dt': 1717094552,\n",
        "'sys':\n",
        "    {'type': 2,\n",
        "    'id': 2075535,\n",
        "    'country': 'GB',\n",
        "    'sunrise': 1717041032,\n",
        "    'sunset': 1717099560},\n",
        "'timezone': 3600,\n",
        "'id': 2643743,\n",
        "'name': 'London',\n",
        "'cod': 200}\n",
        "```\n",
        "\n"
      ],
      "metadata": {
        "id": "iMR5d3uY1ceg"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Response Objects: Attributes and Methods\n",
        "\n",
        "When you make a request using the Python requests library, the response is an instance of the Response class. This object contains a variety of attributes and methods that allow you to inspect the result of your request.\n",
        "\n",
        "Here are the key attributes and methods of a Response object:\n",
        "\n",
        "Attributes\n",
        "\n",
        "* status_code: The HTTP status code returned by the server.\n",
        "* * response.status_code\n",
        "* headers: A dictionary of response headers.\n",
        "* * response.headers\n",
        "* encoding: The encoding used to decode the response content. If not specified, this is guessed based on the response headers.\n",
        "* * response.encoding\n",
        "* content: The raw content of the response, in bytes.\n",
        "* * response.content\n",
        "* text: The content of the response, in unicode.\n",
        "* * response.text\n",
        "* url: The final URL location of the response (after any redirects).\n",
        "* * response.url\n",
        "* elapsed: A timedelta object representing the time elapsed between sending the request and receiving the response.\n",
        "* * response.elapsed\n",
        "cookies: A RequestsCookieJar object containing the cookies sent back by the server.\n",
        "\n",
        "Methods\n",
        "\n",
        "* json(): A method that parses the response content and returns it as a JSON object (assuming the response content is JSON).\n",
        "* * response.json()\n",
        "* raise_for_status(): Raises an HTTPError if the HTTP request returned an unsuccessful status code.\n",
        "* * response.raise_for_status()\n",
        "* close(): Closes the connection to the server.\n",
        "* * response.close()\n",
        "* iter_content(chunk_size=1, decode_unicode=False): Iterates over the response content in chunk_size blocks. This is useful for downloading large files.\n",
        "* * for chunk in response.iter_content(chunk_size=1024): Process chunk\n",
        "* iter_lines(chunk_size=512, decode_unicode=False, delimiter=None): Iterates over the response data, one line at a time. This is useful for reading streaming APIs.\n",
        "* * for line in response.iter_lines(): Process line"
      ],
      "metadata": {
        "id": "CV2OZiK62cRm"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Check if the request was successful\n",
        "if response.status_code == 200:\n",
        "    print(\"Status Code:\", response.status_code)\n",
        "    print(\"Headers:\", response.headers)\n",
        "    print(\"Encoding:\", response.encoding)\n",
        "    print(\"Content (bytes):\", response.content)\n",
        "    print(\"Text (string):\", response.text)\n",
        "    print(\"JSON:\", response.json())\n",
        "    print(\"URL:\", response.url)\n",
        "    print(\"History:\", response.history)\n",
        "    print(\"Elapsed Time:\", response.elapsed)\n",
        "    print(\"Cookies:\", response.cookies)\n",
        "    print(\"Reason:\", response.reason)\n",
        "    print(\"Request:\", response.request)\n",
        "else:\n",
        "    print(f\"Error: {response.status_code}\")\n",
        "    response.raise_for_sta"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xaK7czbm2bRG",
        "outputId": "2c8a4adf-0b48-4b18-c720-3ff0a0038048"
      },
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Status Code: 200\n",
            "Headers: {'Server': 'openresty', 'Date': 'Thu, 05 Sep 2024 09:00:53 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '507', 'Connection': 'keep-alive', 'X-Cache-Key': '/data/2.5/weather?q=marrakesh&units=metric', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Methods': 'GET, POST'}\n",
            "Encoding: utf-8\n",
            "Content (bytes): b'{\"coord\":{\"lon\":-8.0083,\"lat\":31.6315},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03d\"}],\"base\":\"stations\",\"main\":{\"temp\":27.04,\"feels_like\":27.1,\"temp_min\":27.04,\"temp_max\":32.42,\"pressure\":1010,\"humidity\":44,\"sea_level\":1010,\"grnd_level\":956},\"visibility\":10000,\"wind\":{\"speed\":1.54,\"deg\":30},\"clouds\":{\"all\":40},\"dt\":1725526824,\"sys\":{\"type\":1,\"id\":2409,\"country\":\"MA\",\"sunrise\":1725516626,\"sunset\":1725562274},\"timezone\":3600,\"id\":2542997,\"name\":\"Marrakesh\",\"cod\":200}'\n",
            "Text (string): {\"coord\":{\"lon\":-8.0083,\"lat\":31.6315},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03d\"}],\"base\":\"stations\",\"main\":{\"temp\":27.04,\"feels_like\":27.1,\"temp_min\":27.04,\"temp_max\":32.42,\"pressure\":1010,\"humidity\":44,\"sea_level\":1010,\"grnd_level\":956},\"visibility\":10000,\"wind\":{\"speed\":1.54,\"deg\":30},\"clouds\":{\"all\":40},\"dt\":1725526824,\"sys\":{\"type\":1,\"id\":2409,\"country\":\"MA\",\"sunrise\":1725516626,\"sunset\":1725562274},\"timezone\":3600,\"id\":2542997,\"name\":\"Marrakesh\",\"cod\":200}\n",
            "JSON: {'coord': {'lon': -8.0083, 'lat': 31.6315}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': 'scattered clouds', 'icon': '03d'}], 'base': 'stations', 'main': {'temp': 27.04, 'feels_like': 27.1, 'temp_min': 27.04, 'temp_max': 32.42, 'pressure': 1010, 'humidity': 44, 'sea_level': 1010, 'grnd_level': 956}, 'visibility': 10000, 'wind': {'speed': 1.54, 'deg': 30}, 'clouds': {'all': 40}, 'dt': 1725526824, 'sys': {'type': 1, 'id': 2409, 'country': 'MA', 'sunrise': 1725516626, 'sunset': 1725562274}, 'timezone': 3600, 'id': 2542997, 'name': 'Marrakesh', 'cod': 200}\n",
            "URL: http://api.openweathermap.org/data/2.5/weather?q=Marrakesh&appid=cd30189c3ebf97e39e3a734e6ffb2534&units=metric\n",
            "History: []\n",
            "Elapsed Time: 0:00:00.044050\n",
            "Cookies: <RequestsCookieJar[]>\n",
            "Reason: OK\n",
            "Request: <PreparedRequest [GET]>\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Using an incorrect key to test error handling\n",
        "owm_api_key_incorrect = \"cd30189c3ebf97e39e3a734e6ffb253\"\n",
        "\n",
        "# Parameters for the API request\n",
        "incorrect_key_params = {\n",
        "    'q': 'London',              # City name\n",
        "    'appid': owm_api_key_incorrect,       # Your API key\n",
        "    'units': 'metric'           # Units of measurement (metric, imperial, or standard)\n",
        "}\n",
        "\n",
        "# Make the GET request\n",
        "response_incorrect_key = requests.get(owm_endpoint, params= incorrect_key_params)"
      ],
      "metadata": {
        "id": "NrmYtjqC32N8"
      },
      "execution_count": 28,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Raise an exception if the request was unsuccessful\n",
        "try:\n",
        "    response_incorrect_key.raise_for_status()\n",
        "    print(\"Request was successful.\")\n",
        "except requests.exceptions.HTTPError as e:\n",
        "    print(f\"HTTPError: {e}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "z51t4wB-2KG-",
        "outputId": "78f5c34b-8eda-4d2a-b61d-66944463623e"
      },
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "HTTPError: 401 Client Error: Unauthorized for url: http://api.openweathermap.org/data/2.5/weather?q=London&appid=cd30189c3ebf97e39e3a734e6ffb253&units=metric\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Parse the response content as JSON\n",
        "try:\n",
        "    json_data = response.json()\n",
        "    print(\"JSON data:\", json_data)\n",
        "except ValueError:\n",
        "    print(\"Response content is not valid JSON.\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "4CubrrGn3wif",
        "outputId": "ba4bf3c2-060c-40f2-824b-b9c53739f698"
      },
      "execution_count": 30,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "JSON data: {'coord': {'lon': -8.0083, 'lat': 31.6315}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': 'scattered clouds', 'icon': '03d'}], 'base': 'stations', 'main': {'temp': 27.04, 'feels_like': 27.1, 'temp_min': 27.04, 'temp_max': 32.42, 'pressure': 1010, 'humidity': 44, 'sea_level': 1010, 'grnd_level': 956}, 'visibility': 10000, 'wind': {'speed': 1.54, 'deg': 30}, 'clouds': {'all': 40}, 'dt': 1725526824, 'sys': {'type': 1, 'id': 2409, 'country': 'MA', 'sunrise': 1725516626, 'sunset': 1725562274}, 'timezone': 3600, 'id': 2542997, 'name': 'Marrakesh', 'cod': 200}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 14. Iterate over the response content in chunks\n",
        "print(\"Iterating over content in chunks:\")\n",
        "for chunk in response.iter_content(chunk_size=20):  # Print the first chunk\n",
        "    print(chunk)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "MLJ3OzGz3xw6",
        "outputId": "1d5a0c3d-f8d7-417b-aadf-30b4c3b1bb00"
      },
      "execution_count": 31,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Iterating over content in chunks:\n",
            "b'{\"coord\":{\"lon\":-8.0'\n",
            "b'083,\"lat\":31.6315},\"'\n",
            "b'weather\":[{\"id\":802,'\n",
            "b'\"main\":\"Clouds\",\"des'\n",
            "b'cription\":\"scattered'\n",
            "b' clouds\",\"icon\":\"03d'\n",
            "b'\"}],\"base\":\"stations'\n",
            "b'\",\"main\":{\"temp\":27.'\n",
            "b'04,\"feels_like\":27.1'\n",
            "b',\"temp_min\":27.04,\"t'\n",
            "b'emp_max\":32.42,\"pres'\n",
            "b'sure\":1010,\"humidity'\n",
            "b'\":44,\"sea_level\":101'\n",
            "b'0,\"grnd_level\":956},'\n",
            "b'\"visibility\":10000,\"'\n",
            "b'wind\":{\"speed\":1.54,'\n",
            "b'\"deg\":30},\"clouds\":{'\n",
            "b'\"all\":40},\"dt\":17255'\n",
            "b'26824,\"sys\":{\"type\":'\n",
            "b'1,\"id\":2409,\"country'\n",
            "b'\":\"MA\",\"sunrise\":172'\n",
            "b'5516626,\"sunset\":172'\n",
            "b'5562274},\"timezone\":'\n",
            "b'3600,\"id\":2542997,\"n'\n",
            "b'ame\":\"Marrakesh\",\"co'\n",
            "b'd\":200}'\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# 15. Iterate over the response content line by line\n",
        "print(\"Iterating over content line by line:\")\n",
        "for line in response.iter_lines(decode_unicode=True):  # Print the first line\n",
        "    print(line)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "pbNzR2FP4VqQ",
        "outputId": "a8d6d4a1-0f83-4693-fd5d-84662e19f2ac"
      },
      "execution_count": 32,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Iterating over content line by line:\n",
            "{\"coord\":{\"lon\":-8.0083,\"lat\":31.6315},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03d\"}],\"base\":\"stations\",\"main\":{\"temp\":27.04,\"feels_like\":27.1,\"temp_min\":27.04,\"temp_max\":32.42,\"pressure\":1010,\"humidity\":44,\"sea_level\":1010,\"grnd_level\":956},\"visibility\":10000,\"wind\":{\"speed\":1.54,\"deg\":30},\"clouds\":{\"all\":40},\"dt\":1725526824,\"sys\":{\"type\":1,\"id\":2409,\"country\":\"MA\",\"sunrise\":1725516626,\"sunset\":1725562274},\"timezone\":3600,\"id\":2542997,\"name\":\"Marrakesh\",\"cod\":200}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "main_weather = json_data['weather'][0]['main']"
      ],
      "metadata": {
        "id": "ukSz7ESF31SE"
      },
      "execution_count": 33,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "for key, value in json_data['weather'][0].items():\n",
        "  print(key, \":\", value, \"\\n\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "OhqXKfgk3USV",
        "outputId": "9fa82c49-34ce-4ac5-e661-55dd246bddbb"
      },
      "execution_count": 34,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "id : 802 \n",
            "\n",
            "main : Clouds \n",
            "\n",
            "description : scattered clouds \n",
            "\n",
            "icon : 03d \n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Going Further than the Basics\n",
        "\n",
        "The OpenWeatherMap API provides a variety of endpoints and parameters that allow you to access different types of weather data. Below are some of the key endpoints and parameters you can use to explore various features of the OpenWeatherMap API.\n",
        "\n",
        "Note: The OpenWeatherMap API supports a variety of languages for the response data. Here are the valid inputs for the lang parameter, which you can use to get the weather information in different languages:\n",
        "E.g. English: 'en', Spanish 'es', Hindi, 'hi', Arabic 'ar'.\n",
        "\n",
        "Common Parameters:\n",
        "\n",
        "* q: City name (e.g., London)\n",
        "* id: City ID\n",
        "* lat: Latitude\n",
        "* lon: Longitude\n",
        "* zip: ZIP code (e.g., 94040,us)\n",
        "* appid: Your API key\n",
        "* units: Units of measurement (standard, metric, imperial)\n",
        "* lang: Language (e.g., en, es, fr)\n"
      ],
      "metadata": {
        "id": "Lm7Mn4d_4kom"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "current_weather_data_endpoint = \"http://api.openweathermap.org/data/2.5/weather\"\n",
        "\n",
        "params_weather = {\n",
        "    'q': 'London',\n",
        "    'lat': 51.5074, # latitude\n",
        "    'lon': -0.1278, # longitude\n",
        "    'appid': owm_api_key,\n",
        "    'units': 'metric',\n",
        "    'lang' : 'de'\n",
        "}"
      ],
      "metadata": {
        "id": "5DDc8oOg4s2f"
      },
      "execution_count": 35,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "five_day_weather_forecast_endpoint = \"http://api.openweathermap.org/data/2.5/forecast\"\n",
        "\n",
        "params_forecast = {\n",
        "    'q': 'London',\n",
        "    'lat': 51.5074,\n",
        "    'lon': -0.1278,\n",
        "    'appid': owm_api_key,\n",
        "    'units': 'metric',\n",
        "    'lang':'de'}\n"
      ],
      "metadata": {
        "id": "rqWRagQ-41Br"
      },
      "execution_count": 36,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "one_call_endpoint = \"http://api.openweathermap.org/data/2.5/onecall\"\n",
        "\n",
        "params_onecall = {\n",
        "    'lat': 51.5074,\n",
        "    'lon': -0.1278,\n",
        "    #'exclude': #Parts to exclude from the response (current, minutely, hourly, daily, alerts)\n",
        "    'appid': owm_api_key,\n",
        "    'units': 'metric'\n",
        "}"
      ],
      "metadata": {
        "id": "AEo8amJZ45Rc"
      },
      "execution_count": 37,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "historical_weather_endpoint = 'http://api.openweathermap.org/data/2.5/timemachine'\n",
        "\n",
        "params_historical = {\n",
        "    'lat': 51.5074,\n",
        "    'lon': -0.1278,\n",
        "    'dt': 1618317040,  # Example timestamp\n",
        "    'appid': owm_api_key,\n",
        "    'units': 'metric'\n",
        "}"
      ],
      "metadata": {
        "id": "sX_bjo-L4-VW"
      },
      "execution_count": 38,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "air_pollution_endpoint = 'http://api.openweathermap.org/data/2.5/air_pollution'\n",
        "\n",
        "# this endpoint does not accept any other parameters\n",
        "params_air_pollution = {\n",
        "    'lat': 51.5074,\n",
        "    'lon': -0.1278,\n",
        "    'appid': owm_api_key\n",
        "}\n"
      ],
      "metadata": {
        "id": "gvjPkCi04_a1"
      },
      "execution_count": 39,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Make requests to different endpoints\n",
        "response_weather = requests.get(current_weather_data_endpoint, params=params_weather)\n",
        "response_forecast = requests.get(five_day_weather_forecast_endpoint, params=params_forecast)\n",
        "response_onecall = requests.get(one_call_endpoint, params=params_onecall)\n",
        "response_historical = requests.get(historical_weather_endpoint, params=params_historical)\n",
        "response_air_pollution = requests.get(air_pollution_endpoint, params=params_air_pollution)\n",
        "\n",
        "# Print responses\n",
        "print(\"Current Weather Data:\", response_weather.json())\n",
        "print(\"5-Day Weather Forecast:\", response_forecast.json())\n",
        "print(\"One Call API Data:\", response_onecall.json())\n",
        "print(\"Historical Weather Data:\", response_historical.json())\n",
        "print(\"Air Pollution Data:\", response_air_pollution.json())"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "msSG6TCk5Sjs",
        "outputId": "71d2abc1-c714-4ea0-a5f9-eb564b39f59a"
      },
      "execution_count": 40,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Current Weather Data: {'coord': {'lon': -0.1257, 'lat': 51.5085}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'base': 'stations', 'main': {'temp': 15.1, 'feels_like': 15.07, 'temp_min': 13.98, 'temp_max': 15.99, 'pressure': 1013, 'humidity': 92, 'sea_level': 1013, 'grnd_level': 1009}, 'visibility': 10000, 'wind': {'speed': 3.09, 'deg': 350}, 'rain': {'1h': 0.26}, 'clouds': {'all': 100}, 'dt': 1725526687, 'sys': {'type': 2, 'id': 268730, 'country': 'GB', 'sunrise': 1725513608, 'sunset': 1725561509}, 'timezone': 3600, 'id': 2643743, 'name': 'London', 'cod': 200}\n",
            "5-Day Weather Forecast: {'cod': '200', 'message': 0, 'cnt': 40, 'list': [{'dt': 1725537600, 'main': {'temp': 16.95, 'feels_like': 16.89, 'temp_min': 16.95, 'temp_max': 20.52, 'pressure': 1012, 'sea_level': 1012, 'grnd_level': 1006, 'humidity': 84, 'temp_kf': -3.57}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 6.9, 'deg': 31, 'gust': 11.85}, 'visibility': 10000, 'pop': 0.2, 'rain': {'3h': 0.13}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-05 12:00:00'}, {'dt': 1725548400, 'main': {'temp': 19.38, 'feels_like': 19.46, 'temp_min': 19.38, 'temp_max': 21.48, 'pressure': 1010, 'sea_level': 1010, 'grnd_level': 1004, 'humidity': 80, 'temp_kf': -2.1}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 5.32, 'deg': 48, 'gust': 11.33}, 'visibility': 10000, 'pop': 0.2, 'rain': {'3h': 0.23}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-05 15:00:00'}, {'dt': 1725559200, 'main': {'temp': 21.02, 'feels_like': 21.21, 'temp_min': 21.02, 'temp_max': 21.02, 'pressure': 1009, 'sea_level': 1009, 'grnd_level': 1004, 'humidity': 78, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 3.76, 'deg': 81, 'gust': 8.76}, 'visibility': 10000, 'pop': 0.07, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-05 18:00:00'}, {'dt': 1725570000, 'main': {'temp': 20.05, 'feels_like': 20.3, 'temp_min': 20.05, 'temp_max': 20.05, 'pressure': 1010, 'sea_level': 1010, 'grnd_level': 1005, 'humidity': 84, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 100}, 'wind': {'speed': 2.26, 'deg': 74, 'gust': 5.31}, 'visibility': 10000, 'pop': 0.5, 'rain': {'3h': 0.36}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-05 21:00:00'}, {'dt': 1725580800, 'main': {'temp': 18.43, 'feels_like': 18.84, 'temp_min': 18.43, 'temp_max': 18.43, 'pressure': 1009, 'sea_level': 1009, 'grnd_level': 1005, 'humidity': 96, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 100}, 'wind': {'speed': 1.21, 'deg': 35, 'gust': 2.34}, 'visibility': 10000, 'pop': 0.96, 'rain': {'3h': 1.2}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-06 00:00:00'}, {'dt': 1725591600, 'main': {'temp': 17.79, 'feels_like': 18.13, 'temp_min': 17.79, 'temp_max': 17.79, 'pressure': 1009, 'sea_level': 1009, 'grnd_level': 1004, 'humidity': 96, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 97}, 'wind': {'speed': 1.17, 'deg': 5, 'gust': 2.42}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 0.67}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-06 03:00:00'}, {'dt': 1725602400, 'main': {'temp': 17.79, 'feels_like': 18.11, 'temp_min': 17.79, 'temp_max': 17.79, 'pressure': 1009, 'sea_level': 1009, 'grnd_level': 1005, 'humidity': 95, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 96}, 'wind': {'speed': 0.94, 'deg': 12, 'gust': 1.78}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 1.52}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-06 06:00:00'}, {'dt': 1725613200, 'main': {'temp': 17.7, 'feels_like': 17.98, 'temp_min': 17.7, 'temp_max': 17.7, 'pressure': 1010, 'sea_level': 1010, 'grnd_level': 1005, 'humidity': 94, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 99}, 'wind': {'speed': 2.16, 'deg': 228, 'gust': 2.43}, 'visibility': 10000, 'pop': 0.98, 'rain': {'3h': 0.81}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-06 09:00:00'}, {'dt': 1725624000, 'main': {'temp': 16.73, 'feels_like': 16.89, 'temp_min': 16.73, 'temp_max': 16.73, 'pressure': 1010, 'sea_level': 1010, 'grnd_level': 1006, 'humidity': 93, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 3.08, 'deg': 213, 'gust': 4.86}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 1.65}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-06 12:00:00'}, {'dt': 1725634800, 'main': {'temp': 16.73, 'feels_like': 16.81, 'temp_min': 16.73, 'temp_max': 16.73, 'pressure': 1010, 'sea_level': 1010, 'grnd_level': 1006, 'humidity': 90, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 2.21, 'deg': 204, 'gust': 3.65}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 0.65}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-06 15:00:00'}, {'dt': 1725645600, 'main': {'temp': 17.39, 'feels_like': 17.43, 'temp_min': 17.39, 'temp_max': 17.39, 'pressure': 1011, 'sea_level': 1011, 'grnd_level': 1007, 'humidity': 86, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 1.56, 'deg': 174, 'gust': 3.78}, 'visibility': 10000, 'pop': 0.76, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-06 18:00:00'}, {'dt': 1725656400, 'main': {'temp': 15.7, 'feels_like': 15.62, 'temp_min': 15.7, 'temp_max': 15.7, 'pressure': 1012, 'sea_level': 1012, 'grnd_level': 1008, 'humidity': 88, 'temp_kf': 0}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': 'Mäßig bewölkt', 'icon': '03n'}], 'clouds': {'all': 25}, 'wind': {'speed': 0.73, 'deg': 32, 'gust': 0.74}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-06 21:00:00'}, {'dt': 1725667200, 'main': {'temp': 15.23, 'feels_like': 15.16, 'temp_min': 15.23, 'temp_max': 15.23, 'pressure': 1012, 'sea_level': 1012, 'grnd_level': 1008, 'humidity': 90, 'temp_kf': 0}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': 'Mäßig bewölkt', 'icon': '03n'}], 'clouds': {'all': 45}, 'wind': {'speed': 1.59, 'deg': 74, 'gust': 1.88}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-07 00:00:00'}, {'dt': 1725678000, 'main': {'temp': 14.9, 'feels_like': 14.77, 'temp_min': 14.9, 'temp_max': 14.9, 'pressure': 1013, 'sea_level': 1013, 'grnd_level': 1008, 'humidity': 89, 'temp_kf': 0}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'Überwiegend bewölkt', 'icon': '04n'}], 'clouds': {'all': 82}, 'wind': {'speed': 1.58, 'deg': 84, 'gust': 3.33}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-07 03:00:00'}, {'dt': 1725688800, 'main': {'temp': 15.23, 'feels_like': 15.05, 'temp_min': 15.23, 'temp_max': 15.23, 'pressure': 1012, 'sea_level': 1012, 'grnd_level': 1008, 'humidity': 86, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04d'}], 'clouds': {'all': 91}, 'wind': {'speed': 1.56, 'deg': 51, 'gust': 4.14}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-07 06:00:00'}, {'dt': 1725699600, 'main': {'temp': 17.51, 'feels_like': 17.25, 'temp_min': 17.51, 'temp_max': 17.51, 'pressure': 1012, 'sea_level': 1012, 'grnd_level': 1008, 'humidity': 74, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 2.09, 'deg': 50, 'gust': 4.19}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-07 09:00:00'}, {'dt': 1725710400, 'main': {'temp': 20.03, 'feels_like': 19.63, 'temp_min': 20.03, 'temp_max': 20.03, 'pressure': 1012, 'sea_level': 1012, 'grnd_level': 1007, 'humidity': 59, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 3.09, 'deg': 46, 'gust': 5.11}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-07 12:00:00'}, {'dt': 1725721200, 'main': {'temp': 22.84, 'feels_like': 22.38, 'temp_min': 22.84, 'temp_max': 22.84, 'pressure': 1009, 'sea_level': 1009, 'grnd_level': 1005, 'humidity': 46, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 3.41, 'deg': 38, 'gust': 5.11}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-07 15:00:00'}, {'dt': 1725732000, 'main': {'temp': 20.93, 'feels_like': 20.57, 'temp_min': 20.93, 'temp_max': 20.93, 'pressure': 1008, 'sea_level': 1008, 'grnd_level': 1004, 'humidity': 57, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04d'}], 'clouds': {'all': 85}, 'wind': {'speed': 2.95, 'deg': 58, 'gust': 7.02}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-07 18:00:00'}, {'dt': 1725742800, 'main': {'temp': 18.93, 'feels_like': 18.68, 'temp_min': 18.93, 'temp_max': 18.93, 'pressure': 1006, 'sea_level': 1006, 'grnd_level': 1002, 'humidity': 69, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04n'}], 'clouds': {'all': 97}, 'wind': {'speed': 4.2, 'deg': 44, 'gust': 11.51}, 'visibility': 10000, 'pop': 0.07, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-07 21:00:00'}, {'dt': 1725753600, 'main': {'temp': 18.29, 'feels_like': 18.55, 'temp_min': 18.29, 'temp_max': 18.29, 'pressure': 1005, 'sea_level': 1005, 'grnd_level': 1000, 'humidity': 91, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 99}, 'wind': {'speed': 4.44, 'deg': 74, 'gust': 10.04}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 2.47}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-08 00:00:00'}, {'dt': 1725764400, 'main': {'temp': 16.48, 'feels_like': 16.66, 'temp_min': 16.48, 'temp_max': 16.48, 'pressure': 1004, 'sea_level': 1004, 'grnd_level': 1000, 'humidity': 95, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 52}, 'wind': {'speed': 3.57, 'deg': 134, 'gust': 8.09}, 'visibility': 10000, 'pop': 0.2, 'rain': {'3h': 0.1}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-08 03:00:00'}, {'dt': 1725775200, 'main': {'temp': 15.44, 'feels_like': 15.44, 'temp_min': 15.44, 'temp_max': 15.44, 'pressure': 1005, 'sea_level': 1005, 'grnd_level': 1001, 'humidity': 92, 'temp_kf': 0}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': 'Mäßig bewölkt', 'icon': '03d'}], 'clouds': {'all': 49}, 'wind': {'speed': 2.79, 'deg': 119, 'gust': 7.94}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-08 06:00:00'}, {'dt': 1725786000, 'main': {'temp': 17.28, 'feels_like': 17.26, 'temp_min': 17.28, 'temp_max': 17.28, 'pressure': 1005, 'sea_level': 1005, 'grnd_level': 1001, 'humidity': 84, 'temp_kf': 0}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'Bedeckt', 'icon': '04d'}], 'clouds': {'all': 100}, 'wind': {'speed': 3.22, 'deg': 117, 'gust': 6.92}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-08 09:00:00'}, {'dt': 1725796800, 'main': {'temp': 18.86, 'feels_like': 18.63, 'temp_min': 18.86, 'temp_max': 18.86, 'pressure': 1005, 'sea_level': 1005, 'grnd_level': 1001, 'humidity': 70, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 4.83, 'deg': 131, 'gust': 6.79}, 'visibility': 10000, 'pop': 0.88, 'rain': {'3h': 0.65}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-08 12:00:00'}, {'dt': 1725807600, 'main': {'temp': 19.79, 'feels_like': 19.42, 'temp_min': 19.79, 'temp_max': 19.79, 'pressure': 1004, 'sea_level': 1004, 'grnd_level': 999, 'humidity': 61, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 95}, 'wind': {'speed': 4.3, 'deg': 92, 'gust': 6.22}, 'visibility': 10000, 'pop': 0.3, 'rain': {'3h': 0.22}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-08 15:00:00'}, {'dt': 1725818400, 'main': {'temp': 16.61, 'feels_like': 16.52, 'temp_min': 16.61, 'temp_max': 16.61, 'pressure': 1004, 'sea_level': 1004, 'grnd_level': 999, 'humidity': 84, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 97}, 'wind': {'speed': 3.81, 'deg': 45, 'gust': 6.94}, 'visibility': 10000, 'pop': 0.79, 'rain': {'3h': 0.62}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-08 18:00:00'}, {'dt': 1725829200, 'main': {'temp': 15.69, 'feels_like': 15.69, 'temp_min': 15.69, 'temp_max': 15.69, 'pressure': 1003, 'sea_level': 1003, 'grnd_level': 999, 'humidity': 91, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 100}, 'wind': {'speed': 3.56, 'deg': 350, 'gust': 7.36}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 1.16}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-08 21:00:00'}, {'dt': 1725840000, 'main': {'temp': 15.42, 'feels_like': 15.5, 'temp_min': 15.42, 'temp_max': 15.42, 'pressure': 1003, 'sea_level': 1003, 'grnd_level': 999, 'humidity': 95, 'temp_kf': 0}, 'weather': [{'id': 501, 'main': 'Rain', 'description': 'Mäßiger Regen', 'icon': '10n'}], 'clouds': {'all': 100}, 'wind': {'speed': 3.97, 'deg': 345, 'gust': 8.32}, 'visibility': 5453, 'pop': 1, 'rain': {'3h': 7.43}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-09 00:00:00'}, {'dt': 1725850800, 'main': {'temp': 15.17, 'feels_like': 15.22, 'temp_min': 15.17, 'temp_max': 15.17, 'pressure': 1002, 'sea_level': 1002, 'grnd_level': 998, 'humidity': 95, 'temp_kf': 0}, 'weather': [{'id': 501, 'main': 'Rain', 'description': 'Mäßiger Regen', 'icon': '10n'}], 'clouds': {'all': 100}, 'wind': {'speed': 3.96, 'deg': 318, 'gust': 8.64}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 8.52}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-09 03:00:00'}, {'dt': 1725861600, 'main': {'temp': 15.11, 'feels_like': 15.18, 'temp_min': 15.11, 'temp_max': 15.11, 'pressure': 1003, 'sea_level': 1003, 'grnd_level': 998, 'humidity': 96, 'temp_kf': 0}, 'weather': [{'id': 501, 'main': 'Rain', 'description': 'Mäßiger Regen', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 4.07, 'deg': 315, 'gust': 9.24}, 'visibility': 3894, 'pop': 1, 'rain': {'3h': 4.47}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-09 06:00:00'}, {'dt': 1725872400, 'main': {'temp': 15.57, 'feels_like': 15.61, 'temp_min': 15.57, 'temp_max': 15.57, 'pressure': 1003, 'sea_level': 1003, 'grnd_level': 999, 'humidity': 93, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 4.45, 'deg': 327, 'gust': 9.25}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 2.53}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-09 09:00:00'}, {'dt': 1725883200, 'main': {'temp': 18.02, 'feels_like': 18.02, 'temp_min': 18.02, 'temp_max': 18.02, 'pressure': 1003, 'sea_level': 1003, 'grnd_level': 999, 'humidity': 82, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 99}, 'wind': {'speed': 4.2, 'deg': 342, 'gust': 7.89}, 'visibility': 9266, 'pop': 1, 'rain': {'3h': 2.84}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-09 12:00:00'}, {'dt': 1725894000, 'main': {'temp': 18.59, 'feels_like': 18.62, 'temp_min': 18.59, 'temp_max': 18.59, 'pressure': 1003, 'sea_level': 1003, 'grnd_level': 999, 'humidity': 81, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 94}, 'wind': {'speed': 4.14, 'deg': 339, 'gust': 7.87}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 2}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-09 15:00:00'}, {'dt': 1725904800, 'main': {'temp': 17.07, 'feels_like': 17.08, 'temp_min': 17.07, 'temp_max': 17.07, 'pressure': 1004, 'sea_level': 1004, 'grnd_level': 1000, 'humidity': 86, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 87}, 'wind': {'speed': 4.33, 'deg': 347, 'gust': 9.8}, 'visibility': 10000, 'pop': 1, 'rain': {'3h': 1.65}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-09 18:00:00'}, {'dt': 1725915600, 'main': {'temp': 16.1, 'feels_like': 16.12, 'temp_min': 16.1, 'temp_max': 16.1, 'pressure': 1006, 'sea_level': 1006, 'grnd_level': 1001, 'humidity': 90, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 94}, 'wind': {'speed': 4.44, 'deg': 336, 'gust': 9.85}, 'visibility': 10000, 'pop': 0.59, 'rain': {'3h': 0.53}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-09 21:00:00'}, {'dt': 1725926400, 'main': {'temp': 15.51, 'feels_like': 15.52, 'temp_min': 15.51, 'temp_max': 15.51, 'pressure': 1006, 'sea_level': 1006, 'grnd_level': 1002, 'humidity': 92, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 94}, 'wind': {'speed': 3.9, 'deg': 320, 'gust': 8.48}, 'visibility': 10000, 'pop': 0.58, 'rain': {'3h': 0.24}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-10 00:00:00'}, {'dt': 1725937200, 'main': {'temp': 14.2, 'feels_like': 14.08, 'temp_min': 14.2, 'temp_max': 14.2, 'pressure': 1006, 'sea_level': 1006, 'grnd_level': 1002, 'humidity': 92, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10n'}], 'clouds': {'all': 100}, 'wind': {'speed': 4.32, 'deg': 298, 'gust': 8.42}, 'visibility': 10000, 'pop': 0.53, 'rain': {'3h': 0.33}, 'sys': {'pod': 'n'}, 'dt_txt': '2024-09-10 03:00:00'}, {'dt': 1725948000, 'main': {'temp': 12.6, 'feels_like': 12.19, 'temp_min': 12.6, 'temp_max': 12.6, 'pressure': 1007, 'sea_level': 1007, 'grnd_level': 1002, 'humidity': 87, 'temp_kf': 0}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'Leichter Regen', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 4.39, 'deg': 297, 'gust': 10.31}, 'visibility': 10000, 'pop': 0.97, 'rain': {'3h': 0.63}, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-10 06:00:00'}, {'dt': 1725958800, 'main': {'temp': 14.05, 'feels_like': 13.23, 'temp_min': 14.05, 'temp_max': 14.05, 'pressure': 1007, 'sea_level': 1007, 'grnd_level': 1003, 'humidity': 66, 'temp_kf': 0}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'Überwiegend bewölkt', 'icon': '04d'}], 'clouds': {'all': 81}, 'wind': {'speed': 4.76, 'deg': 291, 'gust': 7.82}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'd'}, 'dt_txt': '2024-09-10 09:00:00'}], 'city': {'id': 2643743, 'name': 'London', 'coord': {'lat': 51.5085, 'lon': -0.1257}, 'country': 'GB', 'population': 1000000, 'timezone': 3600, 'sunrise': 1725513608, 'sunset': 1725561509}}\n",
            "One Call API Data: {'cod': 401, 'message': 'Invalid API key. Please see https://openweathermap.org/faq#error401 for more info.'}\n",
            "Historical Weather Data: {'cod': '404', 'message': 'Internal error'}\n",
            "Air Pollution Data: {'coord': {'lon': -0.1278, 'lat': 51.5074}, 'list': [{'main': {'aqi': 1}, 'components': {'co': 277.04, 'no': 0.23, 'no2': 17.31, 'o3': 38.62, 'so2': 5.36, 'pm2_5': 5, 'pm10': 5.47, 'nh3': 0.48}, 'dt': 1725526854}]}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Integrating with other Python Libraries and APIs\n",
        "\n",
        "You will have noticed that a couple of endpoints can take latitude and longitude - but what if you don't know this? Use another API!\n",
        "\n",
        "* Go to the GeoCage API website and click on the \"Create Account\" button.\n",
        "* Fill out the registration form with your details.\n",
        "* Once registered, log in to your account and generate an API key.\n",
        "* Use this API key in your requests to authenticate and avoid rate limits.\n",
        "\n",
        "The historical data endpoint also accepts a timestamp - there are other Python libraries such as datertime which can help with this."
      ],
      "metadata": {
        "id": "oFlW8Z6p7REw"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install opencage"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "E5W4KXOcSdTJ",
        "outputId": "c5ff5fd8-3703-46fc-debc-aa38458fd63c"
      },
      "execution_count": 41,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Collecting opencage\n",
            "  Downloading opencage-2.4.0-py3-none-any.whl.metadata (5.8 kB)\n",
            "Requirement already satisfied: Requests>=2.31.0 in /usr/local/lib/python3.10/dist-packages (from opencage) (2.32.3)\n",
            "Collecting backoff>=2.2.1 (from opencage)\n",
            "  Downloading backoff-2.2.1-py3-none-any.whl.metadata (14 kB)\n",
            "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from Requests>=2.31.0->opencage) (3.3.2)\n",
            "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from Requests>=2.31.0->opencage) (3.8)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from Requests>=2.31.0->opencage) (2.0.7)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from Requests>=2.31.0->opencage) (2024.8.30)\n",
            "Downloading opencage-2.4.0-py3-none-any.whl (16 kB)\n",
            "Downloading backoff-2.2.1-py3-none-any.whl (15 kB)\n",
            "Installing collected packages: backoff, opencage\n",
            "Successfully installed backoff-2.2.1 opencage-2.4.0\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from opencage.geocoder import OpenCageGeocode\n",
        "import time\n",
        "from datetime import datetime\n",
        "\n",
        "# Your OpenCage API key\n",
        "OPENCAGE_API_KEY = '63dc84fbd0fe40098f946545d96a7d45'\n",
        "\n",
        "# Initialize the OpenCage geocoder\n",
        "geocoder = OpenCageGeocode(OPENCAGE_API_KEY)\n",
        "\n",
        "# Function to get latitude and longitude for a place name\n",
        "def get_lat_lon(place_name):\n",
        "    results = geocoder.geocode(place_name)\n",
        "    if results and len(results):\n",
        "        first_result = results[0]\n",
        "        return first_result['geometry']['lat'], first_result['geometry']['lng']\n",
        "    else:\n",
        "        return None, None\n",
        "\n",
        "# Function to convert date and time to timestamp\n",
        "def datetime_to_timestamp(date_str, time_str):\n",
        "    # Parse date and time strings\n",
        "    dt = datetime.strptime(date_str + ' ' + time_str, '%Y-%m-%d %H:%M:%S')\n",
        "    # Convert to Unix timestamp\n",
        "    timestamp = int(time.mktime(dt.timetuple()))\n",
        "    return timestamp\n",
        "\n",
        "# Example: Get latitude and longitude for Oxford, UK\n",
        "place_name = \"Oxford, UK\"\n",
        "latitude, longitude = get_lat_lon(place_name)\n",
        "if latitude is not None and longitude is not None:\n",
        "    print(\"Latitude:\", latitude)\n",
        "    print(\"Longitude:\", longitude)\n",
        "else:\n",
        "    print(\"Unable to retrieve latitude and longitude for the place.\")\n",
        "\n",
        "# Example: Convert date and time to timestamp (1st Jan 1980 at midnight)\n",
        "date_str = '1980-01-01'\n",
        "time_str = '00:00:00'\n",
        "timestamp = datetime_to_timestamp(date_str, time_str)\n",
        "print(\"Timestamp:\", timestamp)\n"
      ],
      "metadata": {
        "id": "hNcmD-rR-2Dx",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "8f7d6334-1f93-492b-8124-48c364240505"
      },
      "execution_count": 42,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Latitude: 51.7520131\n",
            "Longitude: -1.2578499\n",
            "Timestamp: 315532800\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# What about other API Python Libraries?\n",
        "\n",
        "**What are urllib3, urllib, and requests Libraries?**\n",
        "**1. urllib3**\n",
        "* Description: urllib3 is a powerful, user-friendly HTTP client for Python.\n",
        "* It provides more control over the connection process, supports connection pooling, retries, and allows fine-grained control over low-level details of HTTP requests.\n",
        "* Common Features:\n",
        "* Connection pooling (reuses connections for better performance).\n",
        "* Built-in retry and timeout handling.\n",
        "* SSL/TLS verification.\n",
        "**2. urllib (specifically urllib.request)**\n",
        "* Description: urllib is a built-in Python library that offers simple modules for working with URLs.\n",
        "* It provides functions to make HTTP requests, download data, and manage URLs. However, it doesn't include features like connection pooling or retries, and its syntax can be less intuitive.\n",
        "* Common Features:\n",
        "* Basic GET, POST, and URL handling capabilities.\n",
        "* Built-in, so no installation is required.\n",
        "3. **requests**\n",
        "* Description: requests is the most popular HTTP library for Python. It provides a simple, human-friendly way to send HTTP/1.1 requests. It's higher-level compared to urllib3 and urllib, handling most common cases like redirects and encoding automatically.\n",
        "* Common Features:\n",
        "* Very easy-to-use API.\n",
        "* Automatically decodes response content.\n",
        "* Handles cookies, sessions, and redirects by default.\n"
      ],
      "metadata": {
        "id": "IWLVDyDnPNh0"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import urllib3\n",
        "import json\n",
        "\n",
        "# Create a PoolManager instance to make requests\n",
        "http = urllib3.PoolManager()\n",
        "\n",
        "# Define the API endpoint and parameters\n",
        "city = \"London\"\n",
        "\n",
        "url = f\"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={owm_api_key}\"\n",
        "\n",
        "# Make the request\n",
        "response = http.request('GET', url)\n",
        "\n",
        "# Convert the response data to JSON\n",
        "weather_data = json.loads(response.data.decode('utf-8'))\n",
        "\n",
        "# Print the weather data\n",
        "print(weather_data)\n"
      ],
      "metadata": {
        "id": "JX6sL2AcPNIR",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e7676883-7e5b-4d78-ccdb-ba269d0fdc12"
      },
      "execution_count": 43,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'coord': {'lon': -0.1257, 'lat': 51.5085}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'light rain', 'icon': '10d'}], 'base': 'stations', 'main': {'temp': 288.25, 'feels_like': 288.22, 'temp_min': 287.13, 'temp_max': 288.81, 'pressure': 1013, 'humidity': 92, 'sea_level': 1013, 'grnd_level': 1009}, 'visibility': 10000, 'wind': {'speed': 3.09, 'deg': 350}, 'rain': {'1h': 0.33}, 'clouds': {'all': 100}, 'dt': 1725526377, 'sys': {'type': 2, 'id': 268730, 'country': 'GB', 'sunrise': 1725513608, 'sunset': 1725561509}, 'timezone': 3600, 'id': 2643743, 'name': 'London', 'cod': 200}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Are there other API tools that I can learn to use?\n",
        "\n",
        "Yes! There's the Postman platform, which we will head over to next! This is a no-code or low-code (depending on your preference) platform for working with APIs.\n"
      ],
      "metadata": {
        "id": "rsl3P5c5ZfAV"
      }
    }
  ]
}