In this tutorial we will run a basic api using flask-restful, it will only have two routes which will be a get and post method for the purpose of demonstration.
What is Flask Restful
Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs. It is a lightweight abstraction that works with your existing ORM/libraries. Flask-RESTful encourages best practices with minimal setup.
If you want to see a basic Flask API post, you can follow the link below: - https://blog.ruanbekker.com/blog/2018/11/27/python-flask-tutorial-series-create-a-hello-world-app-p1/
Installation
Install Flask and Flask Restful:
1 2 |
|
Code
The basic code that we have, is to have two methods available (get and post):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Run the Server
Run the server:
1
|
|
Then make a get request:
1
|
|
The response should be the following:
1 2 3 |
|
Then make a post request:
1
|
|
The response should look something like this:
1 2 3 4 |
|
Integration Tests
We can setup integration tests with unittest
by creating test_api.py
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
Then we can run our test with:
1
|
|
Since our first test is expecting {"hello": "world"}
our test will pass, and our second test we are validating that our post request returns a 200 response code and that our lastname field is of string type.
The output of our tests will show something like this:
1 2 3 4 5 6 7 |
|
More on Flask-Restful
This was a very basic example and their documentation provides a great tutorial on how to extend from this example. This is also a great blogpost on testing rest api’s.
Thank You
Thanks for reading, if you like my content, check out my website, read my newsletter or follow me at @ruanbekker on Twitter.