This is the second part of a series about the Flask framework, a common tool used to create web applications with Python.
Objectives
The part 2 will focus on creating HTTP methods to our web API.
The full example is available here: Python-Flask.
Topics
GET
Create a dictionary called _usersdict to be returned after a GET request:
Access the URL below and see the result:
http://127.0.0.1:5000/users
Create another method to return a user by id:
Access the URL below and see the result:
http://127.0.0.1:5000/user?id=1
Return a user by id passing the parameter in the path:
Access the URL below and see the result:
http://127.0.0.1:5000/user/1
POST
To simulate a POST request, remove all dictionaries from _usersdict:
Create a POST method with the following code:
Execute a POST request sending a new user. You can use the Postman to make the request:
The result will be:
A new user was added to the _usersdict. Make some changes at the _getusers function to search for the user by using multiple properties dynamically, even by considering their types.
Don’t forget to run the POST request every time you save the project because the _usersdict will be resetted! |
---|
This way there will be many possible queries with the same method:
PUT
To update a user, create this method:
Execute a PUT request:
The result will be:
DELETE
To delete a user by id, write this code:
Execute a DELETE request:
The result will be:
Next
We will connect our web API with a local database.