How to use curl in Python

curl is used to transfer data from one system to another VIA URL's using GET, POST, PUT and DELETE methods.

 

To use curl in Python, import the requests package. Then use the functions available within the requests package to transfer data in the method type you require. Here are the most commonly used functions and their syntaxes:

 

  • requests.get(url)
  • requests.post(url, data=dict)
  • requests.put(url, data=dict)
  • requests.delete(url, data=dict)

 

Read more: a more detailed demonstration of HTTP requests using curl in Python.

 

To demonstrate a simple curl operation in Python, let's perform a GET request to example.com and print the status code returned.

 

import requests

url = "https://example.com"
res = requests.get(url)

print(res.status_code)
200

 

To return the text of the document in a GET request, access the requests.Response.text property.

 

Here is another example, which checks if the status code returned is 200 and prints the document text if it is the case.

 

import requests

url = "https://example.com"
res = requests.get(url)

if res.status_code == 200:
   print(res.text)
<!doctype html>
<html>
<head>
   <title>Example Domain</title
...