How to convert a curl command to Python requests Turn a curl command, including Copy as cURL from dev tools, into Python requests, fetch or axios code, and know which options do not carry over.
Updated 2026-12-01. Tool: cURL to Code Converter
The short answer
Map each part of the command to the matching argument: the method to requests.get or requests.post, each -H to the headers dict, -d to data= (or json= for a JSON body) and -u to auth=. curlconverter does it on the command line, and the XUtil converter does it in the browser, for fetch and axios as well.
Get the curl command
Browser dev tools write one for you: in the Network tab, right-click a request and choose Copy as cURL. Browsers offer a version for bash and one for Windows; the bash one is easier to read. The copied command includes your cookies and any authorisation header, so treat it like a password.
By hand
A typical API call:
curl https://api.example.com/users \
-H 'Authorization: Bearer abc123' \
-H 'Content-Type: application/json' \
-d '{"name":"Ada"}'
In Python requests:
import requests
response = requests.post(
'https://api.example.com/users',
headers={'Authorization': 'Bearer abc123'},
json={'name': 'Ada'},
)
print(response.status_code, response.json())
json= serialises the dict and sets Content-Type: application/json, so that header can go. The usual mappings:
curl
requests
-X PUT
requests.put(...)
-H 'Name: value'
headers={'Name': 'value'}
-d 'a=1&b=2'
data={'a': '1', 'b': '2'}
-d '{"a":1}' with a JSON content type
json={'a': 1}
-G -d 'q=x'
params={'q': 'x'}
-u user:pass
auth=('user', 'pass')
-F 'file=@photo.jpg'
files={'file': open('photo.jpg', 'rb')}
-b 'id=1'
cookies={'id': '1'}
-k
verify=False
The same request with fetch and with axios:
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Authorization': 'Bearer abc123', 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ada' }),
});
const { data } = await axios.post('https://api.example.com/users', { name: 'Ada' }, {
headers: { Authorization: 'Bearer abc123' },
});
With curlconverter
curlconverter is an open-source converter with a command-line version. Install it with npm and replace curl with curlconverter. Python requests is the default output; --language picks another, such as javascript or node-axios:
npm install --global curlconverter
curlconverter https://api.example.com/users -H 'Authorization: Bearer abc123'
curlconverter --language node-axios https://api.example.com/users
To convert a whole copied command, word curl included, pipe it in and pass -, for example pbpaste | curlconverter - on macOS. API clients such as Postman and Insomnia can also import a curl command and generate code from it.
What to watch for
Content type : -d sends application/x-www-form-urlencoded unless you set another type. requests sets that type when data= is a dict but sends no content type when it is a string, so a string body copied from curl may need the header added.
Exact bytes : json= re-serialises the body, with spaces after colons and commas. If the server checks a signature over the raw body, send the original string with data= and set the header yourself.
Redirects : curl follows redirects only with -L. requests follows them for every method except HEAD, and fetch and axios follow them too.
Shell syntax : $TOKEN, $(...) and @file are expanded by the shell or by curl, not by a converter. Replace them with real values in the code.
Timeouts : requests waits indefinitely unless you pass timeout=, so add one in production code.
-k : verify=False turns off certificate checks. Do not leave it in production code; point verify= at a CA bundle file for a private certificate authority instead.
Do it in your browser
The cURL to Code Converter turns a pasted curl command, written for bash or Windows cmd, into fetch, axios or Python requests code as you type. It handles shell quoting, joined flags such as -sSL, --json, -u, -F and -G, turns a JSON body into an object literal when that gives back the same JSON, and lists every option it did not carry over, such as proxies and timeouts. It does not expand shell variables or read @ files. The command, and whatever tokens it holds, stays in your browser.
Tools for this Frequently asked questions How do I convert curl to Python requests? Pass the URL to requests.get or requests.post, put each -H header in a headers dict, and pass -d as data= or a JSON body as json=. A converter such as curlconverter or the XUtil cURL converter does the mapping for you. How do I copy a request as curl from Chrome? Open dev tools, go to the Network tab, right-click the request and choose Copy, then Copy as cURL. The command includes cookies and authorisation headers, so do not paste it anywhere you would not paste a password. What is the requests equivalent of curl -k? verify=False. It turns off certificate verification, so use it only against a test server, and pass the path of a CA bundle to verify= when the server uses a private certificate authority. Why does my converted request behave differently from curl? Common causes are a missing Content-Type header for a string body, a redirect that requests followed and curl did not, and shell variables or @file references that were never replaced with real values. JSON Formatter & Validator : Validate, pretty-print or minify JSON.JSON Diff : Compare two JSON documents, ignoring key order and formatting.JSONPath Tester : Query JSON with a JSONPath expression.XML to JSON Converter : Convert between XML and JSON, from text or a file.YAML to JSON Converter : Convert between YAML and JSON, from text or a file.CSV to JSON Converter : Convert between CSV and JSON, from text or a file.JSON to TypeScript : Infer TypeScript interfaces from a JSON sample.JSON to Python Dataclass : Infer Python dataclasses from a JSON sample.JSON to Pydantic Model : Infer Pydantic models from a JSON sample.JSON to Go Struct : Infer Go structs with json tags from a JSON sample.JSON to Rust Struct : Infer Rust structs with serde derives from a JSON sample.JSON to Kotlin : Infer Kotlin data classes from a JSON sample.JSON to C# Class : Infer C# classes from a JSON sample.JSON to Zod Schema : Infer Zod schemas and their TypeScript types from a JSON sample.JSON to Java Class : Infer Java records, ready for Jackson, from a JSON sample.JSON to Swift Struct : Infer Swift Codable structs from a JSON sample.JSON to PHP Class : Infer PHP 8 classes with typed, promoted properties from a JSON sample.TOML to JSON Converter : Convert between TOML and JSON, from text or a file..env to JSON Converter : Convert between .env files and JSON, from text or a file.JSON Schema Generator : Infer a draft 2020-12 JSON Schema from a JSON sample.JSON Schema Validator : Check a JSON document against a JSON Schema and list every error.Base64 Encoder / Decoder : Base64, Base32 and Base58 in both directions.JWT Decoder : Read a token’s header and payload without sending it anywhere.URL Encoder / Decoder : Percent-encode text for URLs, or decode it back.URL Parser : Break a URL into host, path, query and fragment.HTML Entities : Escape &, < and > for HTML, or unescape them.Base64 Image Encoder : Image to a Base64 data URL for CSS or HTML, or decode one back.Text to Binary / Hex Converter : Text to binary, hex, octal or decimal, and back.Base Number Converter : Binary, octal, decimal, hex and any base up to 36.Morse Code Translator : Text to dots and dashes, and back.ROT13 / Caesar Cipher : Shift letters by any amount, or ROT13 in one click.SAML Decoder : Decode a SAMLRequest or SAMLResponse to readable XML, with issuer, NameID, conditions and attributes.Password Generator : Random passwords with length and character-set controls.Hash Generator : MD5, SHA-1, SHA-256, SHA-384, SHA-512 and HMAC for text or a file.Bcrypt Generator : Hash a password with bcrypt, or check one against a hash.AES Encrypt / Decrypt : Encrypt text with a passphrase using AES-256-GCM, or decrypt it.UUID / GUID Generator : One or many UUIDs, version 4 or 7.ULID Generator : Sortable 26-character IDs with a time prefix.Random Number Generator : Random integers in a range, one or many, with or without repeats.Certificate Decoder : Read an X.509 certificate or CSR: subject, issuer, expiry, SANs, key and fingerprints.JWT Encoder & Verifier : Sign a JWT with HS256, HS384 or HS512, or verify a token against a secret or public key.TOTP Code Generator : The current 2FA code for a Base32 secret or otpauth URI, and new secrets with a QR code.RSA & SSH Key Generator : RSA key pairs, and Ed25519 where the browser supports it, as PEM and OpenSSH files.Htpasswd Generator : Create .htpasswd lines with bcrypt, Apache MD5 or SHA-1, or check a password against one.Argon2 Hash Generator : Hash a password with Argon2id, Argon2i or Argon2d, or check one against a hash.Unix Timestamp Converter : Epoch seconds or milliseconds to a readable date, and back.Epoch Clock : The current Unix timestamp, live, in seconds and milliseconds.Timezone Converter : Convert a time between cities, with DST handled.Days Between Dates : The exact time between two dates, in days, weeks, months and years.Age Calculator : Exact age in years, months and days, and the next birthday.Cron Expression Generator : Describe a schedule in words and get the cron expression.Cron Expression Parser : Explain a cron expression in words and list its next run times.Date Calculator : Add or subtract time from a date in any time zone, and count business days.SQL Formatter : Format and indent SQL for any dialect.JavaScript Beautifier : Format minified or messy JavaScript into readable code.HTML Formatter : Indent and tidy HTML, or strip it down to one line.XML Formatter : Pretty-print or minify XML, with error positions.CSS Minifier / Beautifier : Minify CSS, or expand it back to readable rules.HTML to Markdown : Convert HTML to clean Markdown.Markdown Previewer : Render Markdown as you type.Regex Tester : Test a pattern against text with live matches.Regex Cheatsheet : Regular-expression syntax with examples.cURL to Code Converter : Turn a curl command into fetch, axios or Python requests code.String Escape / Unescape : Escape or unescape text for JSON, JavaScript, Python, SQL, CSV, shell and regex.SVG Optimizer : Shrink SVG files with SVGO and compare the result with the original.SVG to JSX Converter : Convert SVG markup to JSX or a typed React component.HTML to JSX Converter : Convert an HTML fragment to JSX that compiles in React.Mermaid Diagram Editor : Write Mermaid code, see the diagram as you type and export it as SVG or PNG.Docker Run to Compose Converter : Turn docker run commands into a Compose file, or a Compose file into docker run commands.Text Compare : Diff by line, word or character, unified or side by side.Text Case Converter : camelCase, snake_case, kebab-case, Title Case and more.Word and Character Counter : Characters, words, lines and bytes.Word Frequency Counter : Which words appear most, and how often.Sort Lines : Sort lines alphabetically, numerically, by length or reversed.Duplicate Line Remover : Keep each line once.Whitespace Remover : Strip line breaks, extra spaces or both.String Reverser / Rotator : Reverse a string or rotate it by n characters.Slug Generator : Turn a title into a URL-safe slug.Lorem Ipsum Generator : Placeholder paragraphs, sentences or words.Find and Replace : Replace every match of plain text or a regular expression, with the matches highlighted.Email and URL Extractor : Pull every email address and link out of text, plus IP addresses and phone numbers on request.Invisible Character Detector : Reveal and remove zero-width spaces, direction controls and other hidden Unicode characters.Markdown Table Generator : Turn CSV, spreadsheet cells or JSON into a Markdown table, or a table back into CSV.ASCII Art Text Generator : Turn text into a large ASCII art banner in one of 19 FIGlet fonts.PX to REM Converter : Pixels to rem, em and points at any base font size, and back.Percentage Calculator : Percent of a number, percentage change, and a value plus or minus a percentage.Aspect Ratio Calculator : Simplify a width and height to a ratio such as 16:9, and scale to a new size.Download Time Calculator : How long a file takes to transfer at a given speed, or the speed a deadline needs.RAID Calculator : Usable space and how many disks can fail for RAID 0, 1, 5, 6, 10 and ZFS RAIDZ.Angle Converter : Degrees, radians, gradians and turns.Area Converter : Square metres, feet, acres and hectares.Bits to Bytes Converter : Bits, bytes and every prefix up to petabytes.Energy Converter : Joules, calories, kilowatt-hours and BTU.Frequency Converter : Hertz, kilohertz, megahertz and RPM.Fuel Economy Converter : Miles per gallon, km per litre and litres per 100 km.Length Converter : Metres, feet, miles, inches and nautical miles.Power Converter : Watts, kilowatts and horsepower.Pressure Converter : Pascals, bar, PSI and atmospheres.Speed Converter : km/h, mph, knots and metres per second.Temperature Converter : Celsius, Fahrenheit and Kelvin.Time Unit Converter : Seconds, minutes, hours, days and beyond.Volume Converter : Litres, gallons, pints and cubic metres.Weight Converter : Kilograms, pounds, ounces and stone.QR Code Generator : QR codes for text, links, Wi-Fi and contacts.Barcode Generator : EAN, UPC, Code 128 and more as SVG or PNG.Barcode / QR Reader : Decode a barcode or QR code from an image.Color Picker : Pick a colour and copy it in every format.Image Converter : Convert between PNG, JPEG and WebP, and resize on the way.Contrast Checker : Contrast ratio of text on a background, against WCAG AA and AAA.Favicon Generator : Every favicon size from one image.Image Compressor : Shrink a JPEG, PNG or WebP in the browser.Gradient Generator : Build a CSS gradient and copy the rule.Box Shadow Generator : Tune a shadow and copy the CSS.Image Resizer & Cropper : Resize by pixels or percentage and crop with a draggable box.EXIF Viewer & Remover : Read a photo’s camera, date and GPS data, and strip it without re-encoding.SVG to PNG Converter : Render an SVG to PNG, JPEG or WebP at any size, with or without a background.Colour Palette from Image : The dominant colours of an image, with their share and CSS or JSON export.Merge PDF : Join several PDFs into one, in the order you choose.Split PDF : Extract pages by range, or split a PDF into one file per page or every N pages.Images to PDF : One image per page, with page size, orientation and margin.CIDR / Subnet Calculator : Network, broadcast, mask and host count for an IPv4 CIDR block.Chmod Calculator : File permissions as octal (755) or symbolic (rwxr-xr-x).HTTP Status Codes : Every HTTP status code with what it means and when to use it.MIME Types : Common MIME types by file extension, searchable.Port Numbers : Well-known and registered TCP and UDP ports and the services behind them.ASCII Table : Every ASCII character with its decimal, hex, octal, binary and HTML code.Emoji List : Every emoji by category: click to copy it, with code points and HTML, JavaScript and CSS escapes.HTTP Headers : Request and response headers with their meaning, an example value and the defining spec.Country Codes : ISO 3166-1 country codes with dialling code, capital, continent, currency and flag.Currency Codes : ISO 4217 currency codes with name, symbol, decimal places and the countries that use each one.JavaScript Key Code Viewer : Press a key to see event.key, event.code, keyCode, location and modifiers.User Agent Parser : Read the browser, engine, operating system and device type out of a user-agent string.IPv6 Subnet Calculator : Range, address count, type and reverse DNS name for an IPv6 prefix, and the subnets inside it.WireGuard Config Generator : Keys, a server wg0.conf and a config with a QR code for each peer, made in the browser.MAC Address Formatter : Convert a MAC address to colon, hyphen, Cisco dotted or bare form and inspect its flag bits.