Skip to content

API > Routes

Main API module.

get_weather_data(id_station_who, start_date, end_date)

Return information about weather.

Return information about weather collected by a station between a start and end date. The interval between start and end date should be less than five weeks.

Column Portuguese Description English Description Measure Unit
Date Data Date -
UTCTime Hora UTC UTCTime -
TotalPrecipitation Precipitação total no horário Total Precipitation at Time mm
AtmosphericPressure Pressão atmosférica ao nível da estação, horária Hourly Atmospheric Pressure mB
MaxAtmosphericPressure Pressão atmosférica máxima na hora anterior (automática) Max Atmospheric Pressure (Auto) mB
MinAtmosphericPressure Pressão atmosférica mínima na hora anterior (automática) Min Atmospheric Pressure (Auto) mB
GlobalRadiation Radiação global Global Radiation Kj/m²
DryBulbTemperature Temperatura do ar - bulbo seco, horária Dry Bulb Air Temperature °C
DewPointTemperature Temperatura do ponto de orvalho Dew Point Temperature °C
MaxTemperaturePreviousHour Temperatura máxima na hora anterior (automática) Max Temperature Previous Hour °C
MinTemperaturePreviousHour Temperatura mínima na hora anterior (automática) Min Temperature Previous Hour °C
MaxDewPointTemperature Temperatura de orvalho máxima na hora anterior (auto) Max Dew Point Temperature (Auto) °C
MinDewPointTemperature Temperatura de orvalho mínima na hora anterior (auto) Min Dew Point Temperature (Auto) °C
MaxRelativeHumidity Umidade relativa máxima na hora anterior (automática) Max Relative Humidity (Auto) %
MinRelativeHumidity Umidade relativa mínima na hora anterior (automática) Min Relative Humidity (Auto) %
HourlyRelativeHumidity Umidade relativa do ar, horária Hourly Relative Humidity %
WindDirectionDegrees Vento, direção horária Hourly Wind Direction ° (gr)
MaxWindGust Vento, rajada máxima Max Wind Gust m/s
WindSpeed Vento, velocidade horária Hourly Wind Speed m/s
Source code in app/main.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
@app.get("/weather/{id_station_who}/{start_date}/{end_date}/", tags=["weather"])  # noqa
def get_weather_data(
    id_station_who: IdStationWhoType,
    start_date: PastDate,
    end_date: PastDate,
):
    """Return information about weather.

    Return information about weather collected by a station between a start
    and end date. The interval between start and end date should be less
    than five weeks.

    | Column                       | Portuguese Description                                   | English Description               | Measure Unit      |
    |------------------------------|----------------------------------------------------------|-----------------------------------|-------------------|
    | Date                         | Data                                                     | Date                              | -                 |
    | UTCTime                      | Hora UTC                                                 | UTCTime                           | -                 |
    | TotalPrecipitation           | Precipitação total no horário                            | Total Precipitation at Time       | mm                |
    | AtmosphericPressure          | Pressão atmosférica ao nível da estação, horária         | Hourly Atmospheric Pressure       | mB                |
    | MaxAtmosphericPressure       | Pressão atmosférica máxima na hora anterior (automática) | Max Atmospheric Pressure (Auto)   | mB                |
    | MinAtmosphericPressure       | Pressão atmosférica mínima na hora anterior (automática) | Min Atmospheric Pressure (Auto)   | mB                |
    | GlobalRadiation              | Radiação global                                          | Global Radiation                  | Kj/m²             |
    | DryBulbTemperature           | Temperatura do ar - bulbo seco, horária                  | Dry Bulb Air Temperature          | °C                |
    | DewPointTemperature          | Temperatura do ponto de orvalho                          | Dew Point Temperature             | °C                |
    | MaxTemperaturePreviousHour   | Temperatura máxima na hora anterior (automática)         | Max Temperature Previous Hour     | °C                |
    | MinTemperaturePreviousHour   | Temperatura mínima na hora anterior (automática)         | Min Temperature Previous Hour     | °C                |
    | MaxDewPointTemperature       | Temperatura de orvalho máxima na hora anterior (auto)    | Max Dew Point Temperature (Auto)  | °C                |
    | MinDewPointTemperature       | Temperatura de orvalho mínima na hora anterior (auto)    | Min Dew Point Temperature (Auto)  | °C                |
    | MaxRelativeHumidity          | Umidade relativa máxima na hora anterior (automática)    | Max Relative Humidity (Auto)      | %                 |
    | MinRelativeHumidity          | Umidade relativa mínima na hora anterior (automática)    | Min Relative Humidity (Auto)      | %                 |
    | HourlyRelativeHumidity       | Umidade relativa do ar, horária                          | Hourly Relative Humidity          | %                 |
    | WindDirectionDegrees         | Vento, direção horária                                   | Hourly Wind Direction             | ° (gr)            |
    | MaxWindGust                  | Vento, rajada máxima                                     | Max Wind Gust                     | m/s               |
    | WindSpeed                    | Vento, velocidade horária                                | Hourly Wind Speed                 | m/s               |


    """
    if start_date > end_date:
        raise HTTPException(
            status_code=422,
            detail="end_date should be after start_date.",
        )

    if end_date > start_date + timedelta(weeks=5):
        raise HTTPException(
            status_code=422,
            detail="Maximum period between start_date and end_date should be 5 weeks.",  # noqa
        )

    query_sql = f"""
                SELECT
                    *
                FROM
                    '{weather_db}'
                WHERE
                    IdStationWho = '{id_station_who}' AND
                    Date >= '{start_date}' AND
                    Date <= '{end_date}'
                """  # nosec B608
    result = query_db(query_sql)

    if result:
        return result
    else:
        raise HTTPException(
            status_code=422,
            detail="There is no data to show. Rewrite your query.",
        )

list_station(id_station_who)

Return information about a selected station using IdStationWho.

Source code in app/main.py
134
135
136
137
138
139
140
141
142
143
144
145
146
@app.get("/stations/{id_station_who}/", tags=["stations"])
def list_station(
    id_station_who: IdStationWhoType,
):
    """Return information about a selected station using IdStationWho."""
    query_sql = f"""SELECT *
                    FROM '{stations_db}'
                    WHERE IdStationWho = '{id_station_who}'"""  # nosec B608
    result = query_db(query_sql)
    if result:
        return result
    else:
        raise HTTPException(status_code=404, detail="Station do not exist.")

list_stations()

Return the following information about all the stations.

  • IdStationWho
  • Region
  • State
  • StationName
  • Latitude
  • Longitude
  • Altitude
  • FoundingDate

Future. This information can be used in the query route to build the SQL statements.

Source code in app/main.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
@app.get("/stations/", tags=["stations"])
def list_stations():
    """
    Return the following information about all the stations.

    - IdStationWho
    - Region
    - State
    - StationName
    - Latitude
    - Longitude
    - Altitude
    - FoundingDate

    *Future.* This information can be used in the query route to build the SQL
    statements.
    """
    query_sql = f"SELECT * FROM '{stations_db}'"  # nosec B608
    return query_db(query_sql)

query_db(sql_query)

Execute a SQL query and return the results in JSON format.

This function takes a SQL query string, executes it using DuckDB, and returns the results as a JSON array. It's designed to provide an easy interface for querying a database and getting the results in a web-friendly format. The response is formatted with 'records' orientation and ISO date format.

Parameters

sql_query : str A SQL query string to be executed in the DuckDB database.

Returns

list A list of dictionaries representing the rows of the query result. Each dictionary corresponds to a row, with column names as keys.

Raises

Exception Raises an exception if the SQL query execution or JSON conversion fails.

Source code in app/main.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def query_db(sql_query: str) -> list:
    """
    Execute a SQL query and return the results in JSON format.

    This function takes a SQL query string, executes it using DuckDB, and
    returns the results as a JSON array. It's designed to provide an easy
    interface for querying a database and getting the results in a
    web-friendly format. The response is formatted with 'records' orientation
    and ISO date format.

    Parameters
    ----------
    sql_query : str
        A SQL query string to be executed in the DuckDB database.

    Returns
    -------
    list
        A list of dictionaries representing the rows of the query result.
        Each dictionary corresponds to a row, with column names as keys.

    Raises
    ------
    Exception
        Raises an exception if the SQL query execution or JSON conversion
        fails.
    """
    try:
        response = (
            duckdb.sql(sql_query)
            .df()
            .to_json(
                orient="records",
                date_format="iso",
            )
        )
        response_json = json.loads(response)
        return response_json
    except Exception as e:
        raise Exception(f"Error in query_db function: {e}")

root()

Redirect user to API documentation.

Source code in app/main.py
61
62
63
64
@app.get("/")
def root() -> None:
    """Redirect user to API documentation."""
    return RedirectResponse(url="/docs")