The device ID API

The route for individual devices specifies that the ID should be an integer, which can act as our first line of defense against a bad request. The two endpoints follow the same design pattern as our /devices/ endpoint, where we use the same import and export functions:

@app.route('/devices/<int:id>', methods=['GET'])
def get_device(id):
return jsonify(Device.query.get_or_404(id).export_data())

@app.route('/devices/<int:id>', methods=['PUT'])
def edit_device(id):
device = Device.query.get_or_404(id)
device.import_data(request.json)
db.session.add(device)
db.session.commit()
return jsonify({})

Notice the query_or_404() method; it provides a convenient way for returning 404 (not found) if the database query returns negative for the ID passed in. This is a pretty elegant way of providing a quick check on the database query.

Finally, the last part of the code creates the database table and starts the Flask development server:

if __name__ == '__main__':
db.create_all()
app.run(host='0.0.0.0', debug=True)

This is one of the longer Python scripts in the book; therefore, we will take more time to explain it in detail. This provides a way to illustrate ways we can utilize the database in the backend to keep track of the network devices and only expose what we need to the external world as APIs, using Flask.

In the next section, we will take a look at how to use API to perform asynchronous tasks to either individual devices or a group of devices.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.216.254