DEV Community

Cover image for Day 2: GET and POST request in Flask
Deepak Raj
Deepak Raj

Posted on • Originally published at codeperfectplus.com on

Day 2: GET and POST request in Flask

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:

  • / - This is the home route. It will return a message that says superheroes API as a response.
  • /superheroes - This route will return all the superheroes data as a response.\
  • /superheroes/<int:id> - This route will return the superhero data with the given id as a response. so if you want to get the superhero data with id 1 then you have to make a GET request to /superheroes/1.
  • /superheroes - This route 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.

How to run the flask application?

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

python app.py

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)