Black Lives Matter. Please consider donating to Black Girls Code today.

Request Error Handling

Hello

What’s the best way to handle request errors? Sometimes it might respond with something unexpected. Maybe a 404 or the data structure has changed.

import dash
import dash_core_components as dcc
import dash_html_components as html
import requests

app = dash.Dash(__name__)


def get_data_from_api():
    # fetch data from an API here.
    return [
        {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
        {'x': [1, 2, 3], 'y': [2, 4, 5],
         'type': 'bar', 'name': u'Montréal'},
    ]


app.layout = html.Div(children=[
    dcc.Graph(
        id='example-graph',
        figure={
            'data': get_data_from_api(),
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)