python requests get or post

hljs.highlightAll();

Python Requests - GET or POST

If you are working with web APIs in Python, you would have come across the term "requests" library. Requests is a popular Python library used to make HTTP requests. It provides an easy-to-use interface for sending HTTP requests and handling their responses.

GET Request

A GET request is used to retrieve data from a server. This means that you send a request to the server with some parameters, and the server responds with the data that matches those parameters.

To make a GET request using requests library, you need to use the requests.get() method. Here's an example:


import requests

response = requests.get('https://jsonplaceholder.typicode.com/todos/1')
print(response.json())
    

In the above example, we are sending a GET request to https://jsonplaceholder.typicode.com/todos/1, which is a public API that returns a JSON object. We are then printing the JSON object returned by the server using the response.json() method.

POST Request

A POST request is used to send data to a server. This means that you send a request to the server with some data in the body of the request, and the server responds with a confirmation that the data has been received.

To make a POST request using requests library, you need to use the requests.post() method. Here's an example:


import requests

data = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = requests.post('https://jsonplaceholder.typicode.com/posts', data=data)
print(response.json())
    

In the above example, we are sending a POST request to https://jsonplaceholder.typicode.com/posts, which is a public API that creates a new post. We are then printing the JSON object returned by the server using the response.json() method.

Conclusion

GET and POST requests are the most commonly used HTTP methods in web APIs. The requests library in Python provides an easy-to-use interface for making HTTP requests. In this article, we have seen how to make GET and POST requests using the requests library.