Skip to content
Muslu Yüksektepe

reqs2curl

A tool that turns a request built with Python requests into an equivalent curl command.

reqs2curl is a small helper that turns an HTTP request sent with Python's requests library into a curl command that makes the same request. I wrote it for Python 3 in 2020. It consists of a single function and has no external dependencies.

Purpose

When working with an API, figuring out why a request did not behave as expected often means trying the same request again in the terminal or sending it to the team on the other side. Converting a request from Python code into a curl command by hand, with all its headers and body, takes time and is easy to get wrong. I made reqs2curl so this conversion takes a single line. curl is a tool for sending HTTP requests from the command line and is available on almost every system.

How it works

When a request is sent with requests, the returned response object also holds the prepared form of the request that was actually sent. The to_curl function takes this prepared request. It first adds the request method to the command with -X. It then turns each header into its own -H option; only the User-Agent header is replaced with a fixed value of my own. If the request has a body stored as bytes, it decodes it to UTF-8 text first and then adds it with -d. Finally it puts the request address at the end of the command.

If the function's second parameter, verify, is set to False, --insecure is added to the command. This makes a request that was sent from requests with SSL certificate checking turned off work the same way in curl.

Key features

  • It gathers the request's method, headers, body and address into one curl command.
  • It turns a body stored as bytes into readable text.
  • It adds the matching curl option for requests sent with certificate checking turned off.

Technical stack

The code is a single Python file with a single function. It builds the command piece by piece with f-strings and joins the pieces with spaces at the end. It does not depend on requests directly; it only reads the fields of the request object that requests produces.

Status

The README example in the repository calls the function convert_curl, while its actual name in the code is to_curl. When using it, the name in the code is the one that works. The project has not been updated since 2020.

Use cases

  • I use it to replay an API request exactly in the terminal while debugging it.
  • I can send the support team of a service I am having integration trouble with the request I made as a runnable command.
  • Generating curl examples from Python code speeds things up when adding sample requests to API documentation.
Category
Developer tools
Year
2020

Technologies

  • Python
  • HTTP
  • CLI

Links

  • GitHub https://github.com/muslu/reqs2curl

Back to all projects