Back to blog

Mastering cURL to Python: The Ultimate Guide for Developers

-
Table of contents
-

cURL is one of the fastest ways to test an API, download a file, or send an HTTP request from a terminal. However, terminal commands are less convenient when a task needs loops, reusable logic, scheduling, or error handling.

That is why developers often convert cURL to Python and use the Requests library instead. In this guide, you will learn how to convert cURL commands, translate common options, handle authentication and uploads, and use automated conversion tools.

What is cURL?

cURL is a command-line tool for transferring data with URLs. It supports HTTP, HTTPS, FTP, and many other protocols, but developers commonly use it for APIs, debugging, file transfers, and quick endpoint tests.

A cURL command is compact and easy to run once. Python requests are usually easier to maintain when the same request becomes part of an application or automation script. When you move commands to Python, you can add conditions, loops, logging, retries, parsing, and other program logic around the request.

Understanding cURL commands

Most cURL commands follow a simple structure:

curl [options] URL

Common options include:

  • -X to specify a method such as GET, POST, PUT, or DELETE
  • -H or --header to add headers
  • -d or --data to send request data
  • -u to provide a username and password
  • -i to include response headers in the output

A basic GET request looks like this:

curl "https://api.example.com/users?page=2"

A POST request with a header and body could look like this:

curl -X POST "https://api.example.com/users" \
 
-H "Content-Type: application/json" \
 
-d '{"name":"Alex"}'

Understanding which flag controls each part makes it much easier to convert cURL commands to Python code. The URL identifies the endpoint, while options define the method, headers, credentials, and body.

Before translating commands to Python, separate those parts mentally. This simple habit makes longer terminal examples much less intimidating.

How to manually convert cURL to Python

Manual conversion is useful because it helps you understand how the pieces of a Python cURL command fit together. A good rule is to convert cURL commands one option at a time. It also helps when an automatic converter produces something unexpected.

Once you can map common commands to Python yourself, debugging generated snippets becomes much faster.

Converting GET requests

To convert cURL for a simple GET, import Requests and call requests.get():

import requests
 
 
params = {"page": 2}
 
headers = {"Accept": "application/json"}
 
 
r = requests.get(
 
    "https://api.example.com/users",
 
    params=params,
 
    headers=headers,
 
    timeout=10
 
)
 
 
print(r.status_code)
 

Query parameters go into params, while cURL -H values become entries in a headers dictionary. This is one of the simplest ways to translate commands to Python and keeps the final URL readable.

For a more complicated GET, you can keep adding key-value pairs to params instead of manually building a long query string.

Converting POST requests

When you convert cURL commands that send form fields, use the data argument:

r = requests.post( "https://api.example.com/login", data={"username": "alex", "password": "secret"} )

For json data, use json= instead:

payload = {"name": "Alex"}
 
 
r = requests.post(
 
    "https://api.example.com/users",
 
    json=payload,
 
    timeout=10
 
)

This is cleaner than manually serializing the body and setting the JSON content type yourself. When moving POST commands to Python, check whether the original body is form-encoded or JSON before choosing data= or json=.

Authentication methods

The cURL -u flag usually maps to HTTP Basic Authentication:

import requests
 
from requests.auth import HTTPBasicAuth
 
 
r = requests.get(
 
    "https://api.example.com/account",
 
    auth=HTTPBasicAuth("user", "password")
 
)

For bearer tokens, convert cURL authentication headers into a normal Python dictionary:

headers = {"Authorization": "Bearer YOUR_TOKEN"}
 
r = requests.get("https://api.example.com/data", headers=headers)

This makes authentication easier to reuse across multiple Python requests.

Handling file uploads

For multipart uploads, Requests accepts a files argument:

with open("report.pdf", "rb") as file:
 
   response = requests.post(
 
        "https://api.example.com/upload",
 
        files={"file": file}
 
    )

Note that cURL --upload-file is different from a multipart form upload. With HTTP(S), it normally performs an upload using PUT. A closer Python equivalent is:

with open("report.pdf", "rb") as file:
 
    response = requests.put(
 
        "https://api.example.com/report.pdf",
 
        data=file
 
    )

Knowing this difference prevents a Python cURL command from silently changing the request format.

SSL certificates and error handling

cURL -k disables certificate verification. The closest Requests option is verify=False, but it should only be used when you understand the security risk.

import requests
 
 
try:
 
    response = requests.get(
 
        "https://api.example.com/data",
 
        timeout=10,
 
        verify=True
 
    )
 
    response.raise_for_status()
 
except requests.exceptions.RequestException as exc:
 
    print(f"Request failed: {exc}")

Timeouts and exceptions are major reasons to convert cURL into a script. Python requests give you clear control over failures instead of leaving error handling to shell logic.

Practical Use cases

Working with APIs (real-world example)

Imagine an API call with a bearer token, custom header, and JSON body:

curl -X POST "https://api.example.com/tasks" \
 
 -H "Authorization: Bearer YOUR_TOKEN" \
 
 -H "Content-Type: application/json" \
 
 -d '{"title":"Check prices","active":true}'

You can convert cURL to this:

import requests
 
 
url = "https://api.example.com/tasks"
 
headers = {"Authorization": "Bearer YOUR_TOKEN"}
 
payload = {"title": "Check prices", "active": True}
 
 
response = requests.post(url, headers=headers, json=payload, timeout=10)
 
response.raise_for_status()
 
 
print(response.json())

The Python code is longer, but it is easier to extend. You can validate the response, save results, add proxy settings, or repeat the request for multiple records.

Automating HTTP requests

A one-off terminal command is convenient. Repetitive work is where commands to Python become more valuable. A script can read inputs from a file, send hundreds of Python requests, process each response, and write results to a database.

You can then run the script with cron on Linux or macOS, Task Scheduler on Windows, or an orchestration platform. This is a common reason developers convert cURL when moving from testing to production automation.

Automated cURL to Python conversion tools

Online converters

cURL Converter is a convenient option when you need to convert cURL commands quickly. Paste the command into the input box, select Python if needed, and copy the generated Python code. It can also accept commands copied from a browser's developer tools.

A simple workflow is:

  1. Copy the cURL command
  2. Paste it into cURL converter
  3. Review the generated Python cURL command
  4. Check headers, cookies, request bodies, and redirects
  5. Test the code before using it in production

Converters save time, but always review the output. Differences in default behavior can matter, especially with redirects, cookies, and uncommon cURL options.

Python libraries

uncurl is a Python package designed to convert cURL requests to Python Requests syntax. You can install it with:

pip install uncurl

Then use it from Python:

import uncurl
 
command = "curl https://example.com -H 'Accept: application/json'"
print(uncurl.parse(command))

It can be useful when you need to convert cURL inside a Python workflow. However, the package has not seen a PyPI release since 2021, so test generated code carefully and consider cURL Converter for broader, more actively maintained conversion support.

Conclusion

The process of learning cURL for Python basically involves the translation of command line options into Requests parameters. The headers would be converted into dictionaries, query string into params, request body into data or json, and authentication into headers/auth.

Begin by mastering how to translate the cURL commands yourself and convert the cURL commands to Python command-by-command. Once you have mastered the translation, you can use automated tools to speed up the repetitive tasks without making the process a black box.

Try out some of the cURL commands, such as GET, POST, authentication, file upload, and error handling, and finally refer to the official cURL and requests documentation.

Learn more
-

Related articles