Python + Flask - Part 2 - HTTP Methods

Oct 19, 2019

titulo

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:

flask04

Access the URL below and see the result:

http://127.0.0.1:5000/users

flask05

Create another method to return a user by id:

flask06

Access the URL below and see the result:

http://127.0.0.1:5000/user?id=1

flask07

Return a user by id passing the parameter in the path:

flask08

Access the URL below and see the result:

http://127.0.0.1:5000/user/1

flask09

POST

To simulate a POST request, remove all dictionaries from _usersdict:

flask10

Create a POST method with the following code:

flask11

Execute a POST request sending a new user. You can use the Postman to make the request:

flask12

The result will be:

flask13

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!

flask14

This way there will be many possible queries with the same method:

flask15

flask16

flask17

PUT

To update a user, create this method:

flask18

Execute a PUT request:

flask19

The result will be:

flask20

DELETE

To delete a user by id, write this code:

flask21

Execute a DELETE request:

flask22

The result will be:

flask23

Next

We will connect our web API with a local database.


Categories:
Tags: