loading...
Cover image for Python + Flask - Part 2 - HTTP Methods

Python + Flask - Part 2 - HTTP Methods

lucianopereira86 profile image LUCIANO DE SOUSA PEREIRA Originally published at lucianopereira.netlify.com ・2 min read

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

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

Posted on by:

lucianopereira86 profile

LUCIANO DE SOUSA PEREIRA

@lucianopereira86

Luciano de Sousa Pereira. Brazilian. Bacharel degree in Computer Engineering. Full Stack Developer with 5 years of experience in multiple frameworks and programming languages.

Discussion

pic
Editor guide