Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

PyBites: How To Build a Simple API with Flask and Unit Test it

$
0
0

REST has gained lot of popularity and is virtually the default architectural style for designing and implementing RESTful web services. Wikipedia states:

Representational state transfer (REST) or RESTful Web services are one way of providing interoperability between computer systems on the Internet. REST-compliant Web services allow requesting systems to access and manipulate textual representations of Web resources using a uniform and predefined set of stateless operations.

Implementing REST APIs in Flask is relatively easy. As this week's challenge is a House Inventory Tracker, lets do CRUD on room items.

Setup

Firstcreate a virtualenv and do pip install Flask .

API code and endpoints

To create a simple API you basically implement the HTTP methods you need, in this case GET, POST, PUT and DELETE, see the full code here , I implemented the following endpoints:

@app.route('/api/v1/items', methods=['GET']) @app.route('/api/v1/items/<int:id>', methods=['GET']) @app.route('/api/v1/items', methods=['POST']) @app.route('/api/v1/items/<int:id>', methods=['PUT']) @app.route('/api/v1/items/<int:id>', methods=['DELETE']) Testing part I) - manually with curl

How to test this? I first lazily put some curl commands in a test script , isn't it cool you can just use curl to test your new shiny API?

$ python test.py # get items curl -i http://127.0.0.1:5000/api/v1/items HTTP/1.0 200 OK ... { "items": [ { "id": 1, "name": "laptop", "value": 1000 }, ... # add item with proper values curl -i -H "Content-Type: application/json" -X POST -d '{"name":"monitor", "value": 200}' http://127.0.0.1:5000/api/v1/items HTTP/1.0 201 CREATED ... { "item": { "id": 4, "name": "monitor", "value": 200 } } ...

However you have to read the output every time you test. Not cool :(

Testing part II) - automation with unittest

Here the whole exercise became pretty interesting, how to test an API?!

Flask makes this pretty easy with the test_client() method you can use in your setUp:

test_client(use_cookies=True, **kwargs)

Creates a test client for this application. For information about unit testing head over to Testing Flask Applications .

You can test response codes and of course see how the data (list of items in this case) changes after each request. The only challenge was the isolation of each unit test: I had to do copy the app.items to a backup variable in setUp (a deepcopy to not leave references around) and pass it back in tearDown. The unit tests are here .

This whole exercise took me some time and it was great learning, not something you get from just reading about it!

next(API)

Since listening to Soft Skills I want to do some time logging to increase my productivity.

What if I can have a simple API where I can send log entries of 'start time - stop time - activity' via a POST request, and retrieve the data with GET for reporting?

Then deploy it somewhere (Heroku?) and set up a webhook in Slack to just input the entries in a dedicated channel and automatically log them to a back-end via the API.

At the time of writing this article I stumbled upon Flask-RESTful and this morning I saw an article on Google Spreadsheets and Python which might be cool to use for this ... stay tuned for a part II article ...

Further reading

Apart from the Flask documentation / links above, Miguel Grinberg has a lot of excellent material on Flask including his Designing a RESTful API with Python and Flask , recommended.


Viewing all articles
Browse latest Browse all 9596

Trending Articles