Day 2: GET and POST request in Flask

Featured image

In this tutorial we will learn how to implement GET and POST request in flask using python 3. for this tutorial, we will use some sample superhero data with the following fields: id, name, email, age, secretIdentity. Users can perform the GET and POST request on this data.

Use can fetch all the superheroes data using the GET request and can add a new superhero using the POST request. we will not use any database for this tutorial. we will use a list of dictionaries to store the data.

Explanation of the code

In the above code, we have created a flask app and we have created a list of dictionaries to store the data. We have created the following routes:

How to run the flask application?

To run the flask application, you have to run the following command.

python app.py

In the above code, we have used the debug=True parameter. It will automatically reload the server when you make any changes in the code. So you don’t have to restart the server again and again.

How to test the GET and POST request?

You can test the GET and POST request using the Postman application. You can download it from here.

To test the GET request, you have to make a GET request to the following URL: http://localhost:5000/superheroes. It will return all the superheroes data as a response.

To test the GET request with id, you have to make a GET request to the following URL: http://localhost:5000/superheroes/1. It will return the superhero data with id 1 as a response.

To test the POST request, you have to make a POST request to the following URL: http://localhost:5000/superheroes. It will add a new superhero to the list of superheroes. It will take the following data as input: name, email, age, secretIdentity. It will return all the superheroes data as a response.

Conclusion

In this tutorial, we have learned how to implement GET and POST request in flask using python 3. We have also learned how to test the GET and POST request using the Postman application. You can find the complete on my GitHub. If you have any questions or suggestions then you can let me know in the comment section below.