curl in python

Curl in Python

Curl is a command-line tool used to transfer data from or to a server. In Python, we can use the 'requests' module to make HTTP requests similar to using curl.

Using requests module

The requests module provides functions to make GET, POST, PUT, DELETE requests and more. Here is an example of making a GET request:


import requests

response = requests.get('https://jsonplaceholder.typicode.com/users')
print(response.content)

In this example, we import the requests module and make a GET request to the specified URL. We print the response content which is in the form of bytes.

We can also make POST requests using the requests module:


import requests

data = {'username': 'john', 'password': 'secret'}
response = requests.post('http://httpbin.org/post', data=data)
print(response.json())

In this example, we make a POST request to the specified URL with some data. We print the response content which is in JSON format.

Using curl command in Python

We can also use the curl command directly in Python using the 'subprocess' module:


import subprocess

cmd = 'curl https://jsonplaceholder.typicode.com/users'
result = subprocess.run(cmd.split(), capture_output=True)
print(result.stdout)

In this example, we use the 'subprocess' module to run the curl command and capture its output. We print the resulting output.

These are just two ways of using curl in Python. Depending on what you're trying to achieve, one method may be better suited than the other.