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 users_dict 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 users_dict:
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 users_dict. Make some changes at the get_users 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 users_dict 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.
Top comments (0)