How to convert CURL to python requests and vice versa


curl and Python requests are both powerful tools for sending HTTP requests. While curl is a command-line tool that allows you to send requests directly from your terminal, Python’s requests library provides a more programmatic way to send requests from within Python code. In this article, we’ll explore how to convert between curl and Python requests, so you can use the tool that makes the most sense for your workflow.

Converting curl to Python requests

The basic syntax of a curl command looks like this:

curl [OPTIONS] URL

When converting a curl command to Python requests, we need to translate the options and URL into Python code.

Here’s an example curl command:

curl -X POST https://example.com/api/v1/users \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{"username": "john_doe", "email": "john_doe@example.com"}'

To convert this curl command to Python requests, we can write the following code:

import requests

url = 'https://example.com/api/v1/users'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
data = {
'username': 'john_doe',
'email': 'john_doe@example.com'
}

response = requests.post(url, headers=headers, json=data)

print(response.status_code)
print(response.json())

In this example, we use the requests.post() method to send a POST request to the URL https://example.com/api/v1/users with the JSON payload {"username": "john_doe", "email": "john_doe@example.com"}. We also include the Content-Type and Authorization headers.

Converting Python requests to curl

Converting Python requests code to a curl command is a bit trickier, as there’s no direct equivalent for the requests library on the command line. However, we can use the –data or -d option to pass data to the curl command, and the -H option to set headers.

Here’s an example Python GET requests script:

import requests

url = 'https://example.com/api/v1/users'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
params = {
'username': 'john_doe',
'sort': 'name',
'order': 'asc'
}

response = requests.get(url, headers=headers, params=params)

print(response.status_code)
print(response.json())

To convert this Python requests code to a curl command, we can use the following command:

curl -X GET 'https://example.com/api/v1/users?username=john_doe&sort=name&order=asc' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY'

In this example, we use the -X GET option to specify that we’re sending a GET request, and we pass the URL and query parameters as a string. We also include the Content-Type and Authorization headers.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC