help me implement api use for getting data in this code import pandas as pd
import logging
import os
from dash import Dash, html, dash_table, dcc
import plotly.express as px
from dash.dependencies import Input, Output
from dash.exceptions import PreventUpdate

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def load_data(filepath):
    if not os.path.exists(filepath):
        logger.error(f"The file {filepath} does not exist.")
        raise FileNotFoundError(f"The file {filepath} does not exist.")

    columns_to_use = ['dt', 'Country', 'AverageTemperature']
    try:
        df = pd.read_csv(filepath, usecols=columns_to_use, parse_dates=['dt'])
        logger.info("CSV file loaded successfully.")
    except ValueError as error:
        logger.error(f"Error reading the CSV file: {error}")
        raise ValueError(f"Error reading the file: {error}")

    required_cols = {'dt', 'Country', 'AverageTemperature'}
    if not required_cols.issubset(df.columns):
        missing = required_cols - set(df.columns)
        logger.error(f"The required columns are missing: {missing}")
        raise ValueError(f"The required columns are missing: {missing}")

    df.rename(columns={'dt': 'Date and Time'}, inplace=True)
    logger.info("Column 'dt' renamed to 'Date and Time'.")

    initial_row_count = df.shape[0]
    df.dropna(subset=['AverageTemperature'], inplace=True)
    final_row_count = df.shape[0]
    logger.info(f"Dropped {initial_row_count - final_row_count} rows with NaN 'AverageTemperature'.")

    return df

def filter_country_data(country_df):
    country_df.set_index('Date and Time', inplace=True)
    country_df.sort_index(inplace=True)
    logger.info("DataFrame filtered by country and indexed by 'Date and Time'.")
    return country_df

def calculate_moving_average(country_df, window_size=5):
    numeric_cols = country_df.select_dtypes(include='number').columns.tolist()
    logger.debug(f"Numeric columns selected for aggregation: {numeric_cols}")

    if 'AverageTemperature' not in numeric_cols:
        logger.error("The 'AverageTemperature' column is missing or non-numeric.")
        raise ValueError("The 'AverageTemperature' column is missing or non-numeric.")

    try:
        # Resample data to 5-year intervals
        resampled_df = country_df[numeric_cols].resample('5Y').mean()
        logger.info("Data resampled to 5-year intervals.")
    except Exception as error:
        logger.error(f"Error during resampling: {error}")
        raise ValueError(f"Error during resampling: {error}")

    # Calculate moving average
    resampled_df['MovingAverage'] = resampled_df['AverageTemperature'].rolling(window=window_size).mean()
    logger.info(f"5-year moving average calculated with window size {window_size}.")

    return resampled_df

def create_bar_chart(bar_df):
    bar_df_reset = bar_df.reset_index()
    fig = px.bar(
        bar_df_reset,
        x='Date and Time',
        y='AverageTemperature',
        title='Average Temperature Over Time'
    )
    fig.update_layout(
        plot_bgcolor='#121212',
        paper_bgcolor='#121212',
        font_color='white',
        xaxis=dict(title='Date and Time', showgrid=False, color='white'),
        yaxis=dict(title='Average Temperature (°C)', showgrid=True, gridcolor='#333', color='white')
    )
    logger.info("Bar chart created.")
    return fig

def create_box_plot(box_df):
    box_df_reset = box_df.reset_index()
    box_df_reset['Year'] = box_df_reset['Date and Time'].dt.year

    fig = px.box(
        box_df_reset,
        x='Year',
        y='AverageTemperature',
        title='Temperature Distribution by Year',
        points='outliers'
    )
    fig.update_layout(
        plot_bgcolor='#121212',
        paper_bgcolor='#121212',
        font_color='white',
        xaxis=dict(title='Year', showgrid=False, color='white'),
        yaxis=dict(title='Average Temperature (°C)', showgrid=True, gridcolor='#333', color='white')
    )
    logger.info("Box plot created.")
    return fig

def create_line_chart(line_df, country_name):
    line_df_reset = line_df.reset_index()
    fig = px.line(
        line_df_reset,
        x='Date and Time',
        y='MovingAverage',
        title=f'5-Year Moving Average Temperature Over Time in {country_name}'
    )
    fig.update_traces(mode='lines', line=dict(color='cyan'))
    fig.update_layout(
        plot_bgcolor='#121212',
        paper_bgcolor='#121212',
        font_color='white',
        xaxis=dict(title='Date and Time', showgrid=False, color='white'),
        yaxis=dict(title='5-Year Moving Average Temperature (°C)', showgrid=True, gridcolor='#333', color='white')
    )
    logger.info("Line chart created.")
    return fig

def create_choropleth_map(full_df):
    map_df = full_df.reset_index()
    map_df['Year'] = map_df['Date and Time'].dt.year
    avg_temp_df = map_df.groupby(['Country', 'Year'])['AverageTemperature'].mean().reset_index()

    fig = px.choropleth(
        avg_temp_df,
        locations='Country',
        locationmode='country names',
        color='AverageTemperature',
        hover_name='Country',
        animation_frame='Year',
        color_continuous_scale='Viridis',
        title='Global Average Temperature by Country Over Time',
        labels={'AverageTemperature': 'Avg Temp (°C)'}
    )
    fig.update_layout(
        plot_bgcolor='#121212',
        paper_bgcolor='#121212',
        font_color='white',
        coloraxis_colorbar=dict(title='Avg Temp (°C)')
    )
    logger.info("Choropleth map created.")
    return fig

def create_app_layout(df):
    return html.Div([
        # Header with integrated controls
        html.Div([
            html.H1("Global Land Temperature Dashboard", style={
                'textAlign': 'center',
                'color': 'white',
                'marginBottom': '10px'
            }),
            html.Div([
                html.Label("Select a Country:", style={
                    'color': 'white',
                    'fontSize': '18px',
                    'textAlign': 'center',
                    'marginBottom': '10px'
                }),
                dcc.Dropdown(
                    id='country-dropdown',
                    options=[{'label': country, 'value': country} for country in sorted(df['Country'].unique())],
                    value='Latvia',
                    placeholder="Select a country",
                    style={
                        'width': '300px',
                        'minWidth': '200px',
                        'margin': '0 auto'
                    }
                )
            ], style={
                'display': 'flex',
                'flexDirection': 'column',
                'alignItems': 'center',
                'marginBottom': '30px'
            }),
        ], style={
            'backgroundColor': '#1e1e1e',
            'padding': '20px 0'
        }),

        # Visualization Section: Data Table and Box Plot
        html.Div([
            html.Div([
                # Data Table
                html.Div([
                    html.H3("Data Table", style={
                        'color': 'white',
                        'textAlign': 'center',
                        'marginBottom': '10px'
                    }),
                    dash_table.DataTable(
                        id='data-table',
                        page_size=10,
                        style_data_conditional=[
                            {
                                'if': {'row_index': 'odd'},
                                'backgroundColor': '#2c2c2c'
                            }
                        ],
                        style_cell={
                            'minWidth': '150px', 'maxWidth': '150px', 'width': '150px',
                            'backgroundColor': '#333',
                            'color': 'white',
                            'border': '1px solid #444',
                            'textAlign': 'center'
                        },
                        style_header={
                            'backgroundColor': '#444',
                            'color': 'white',
                            'border': '1px solid #555',
                            'fontWeight': 'bold'
                        },
                    )
                ], style={
                    'flex': '1',
                    'padding': '10px'
                }),

                # Box Plot
                html.Div([
                    html.H3("Temperature Distribution by Year", style={
                        'color': 'white',
                        'textAlign': 'center',
                        'marginBottom': '10px'
                    }),
                    dcc.Graph(id='box-plot')
                ], style={
                    'flex': '1',
                    'padding': '10px'
                })
            ], style={
                'display': 'flex',
                'flexWrap': 'wrap',
                'justifyContent': 'center',
                'marginBottom': '30px'
            }),

            # Charts Section: Bar Chart and Line Chart
            html.Div([
                html.Div([
                    # Bar Chart
                    html.Div([
                        html.H3("Average Temperature Over Time", style={
                            'color': 'white',
                            'textAlign': 'center',
                            'marginBottom': '10px'
                        }),
                        dcc.Graph(id='bar-chart')
                    ], style={
                        'flex': '1',
                        'padding': '10px'
                    }),

                    # Line Chart
                    html.Div([
                        html.H3("5-Year Moving Average Temperature", style={
                            'color': 'white',
                            'textAlign': 'center',
                            'marginBottom': '10px'
                        }),
                        dcc.Graph(id='line-chart')
                    ], style={
                        'flex': '1',
                        'padding': '10px'
                    })
                ], style={
                    'display': 'flex',
                    'flexWrap': 'wrap',
                    'justifyContent': 'center',
                    'marginBottom': '30px'
                }),
            ]),
        ]),

        # Geographical Visualization: Choropleth Map
        html.Div([
            html.H3("Global Temperature Trends", style={
                'color': 'white',
                'textAlign': 'center',
                'marginBottom': '10px'
            }),
            dcc.Graph(id='choropleth-map', style={'width': '100%', 'height': '800px'})
        ], style={
            'padding': '10px',
            'marginBottom': '30px'
        }),

    ], style={
        'backgroundColor': '#121212',
        'padding': '20px',
        'fontFamily': 'Arial, sans-serif'
    })

def create_dashboard_callbacks(app, df):
    @app.callback(
        [Output('data-table', 'data'),
         Output('line-chart', 'figure'),
         Output('bar-chart', 'figure'),
         Output('box-plot', 'figure'),
         Output('choropleth-map', 'figure')],
        [Input('country-dropdown', 'value')]
    )
    def update_dashboard(selected_country):
        if not selected_country:
            logger.warning("No country selected. Dashboard not updated.")
            raise PreventUpdate

        filtered_df = df[df['Country'] == selected_country].copy()
        if filtered_df.empty:
            logger.warning(f"No data available for country: {selected_country}")
            return [], {}, {}, {}, {}

        try:
            country_filtered_df = filter_country_data(filtered_df)
            country_moving_avg = calculate_moving_average(country_filtered_df)
        except Exception as error:
            logger.error(f"Error processing data for {selected_country}: {error}")
            return [], {}, {}, {}, {}

        # Replace NaN in 'MovingAverage' with 'NaN' string
        table_data = country_moving_avg.reset_index().fillna('NaN').to_dict('records')

        try:
            line_fig = create_line_chart(country_moving_avg, selected_country)
            bar_fig = create_bar_chart(filtered_df)
            box_fig = create_box_plot(filtered_df)
            choropleth_fig = create_choropleth_map(df)
        except Exception as error:
            logger.error(f"Error creating figures: {error}")
            line_fig, bar_fig, box_fig, choropleth_fig = {}, {}, {}, {}

        return table_data, line_fig, bar_fig, box_fig, choropleth_fig

def create_choropleth_map(full_df):
    map_df = full_df.reset_index()
    map_df['Year'] = map_df['Date and Time'].dt.year
    avg_temp_df = map_df.groupby(['Country', 'Year'])['AverageTemperature'].mean().reset_index()

    choropleth_fig = px.choropleth(
        avg_temp_df,
        locations='Country',
        locationmode='country names',
        color='AverageTemperature',
        hover_name='Country',
        animation_frame='Year',
        color_continuous_scale='Viridis',
        title='Global Average Temperature by Country Over Time',
        labels={'AverageTemperature': 'Avg Temp (°C)'}
    )
    choropleth_fig.update_layout(
        plot_bgcolor='#121212',
        paper_bgcolor='#121212',
        font_color='white',
        coloraxis_colorbar=dict(title='Avg Temp (°C)')
    )
    logger.info("Choropleth map created.")
    return choropleth_fig

if __name__ == '__main__':
    DATA_FILE_PATH = 'assets/GlobalLandTemperaturesByCountry.csv'
    try:
        df = load_data(DATA_FILE_PATH)
    except Exception as error:
        logger.critical(f"Application terminated: {error}")
        exit(1)

    app = Dash(__name__)
    app.layout = create_app_layout(df)
    create_dashboard_callbacks(app, df)
    app.run_server(debug=True)