Sunday, January 24, 2021

Convert cURL command to Python Request

cURL stands for Client URL (Uniform Resource Locator). It is a tool to transfer data from or to a server, using any of the supported protocols (HTTP, FTP, IMAP, POP3, SCP, SFTP, SMTP, TFTP, TELNET, LDAP or FILE).

A simple usage call is: curl http://umaryusuf.com

This will return the HTML content of the website page provided as seen below.



cURL is commonly use by service provide to grant access to their API request without depending on any programming language.

As an example, lets convert this sample API Code from ScraperAPI in cURL format to python requests format:-

curl "http://api.scraperapi.com?api_key=we709a6dkbask80kjbaskjoie2nsaqa7&url=http://httpbin.org/ip"


There are several ways to convert cURL to python, the one I use more often is a tool by Nick Carneiro (https://curl.trillworks.com). So, copy and paste the cURL code to generate a python version.


import requests

params = (
    ('api_key', 'we709a6dkbask80kjbaskjoie2nsaqa7'),
    ('url', 'http://httpbin.org/ip'),
)

response = requests.get('http://api.scraperapi.com/', params=params)

#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.get('http://api.scraperapi.com?api_key=we709a6dkbask80kjbaskjoie2nsaqa7&url=http://httpbin.org/ip')

That is it!

No comments:

Post a Comment