Python + Flask - Part 2 - HTTP Methods

lucianopereira86

LUCIANO DE SOUSA PEREIRA

Posted on October 20, 2019

Python + Flask - Part 2 - HTTP Methods

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 users_dict to be returned after a GET request:

flask04

Access the URL below and see the result:

http://127.0.0.1:5000/users
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

flask09

POST

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

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 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!

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.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
lucianopereira86
LUCIANO DE SOUSA PEREIRA

Posted on October 20, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About