JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Implementing Curl command in Python using requests module

Author:JIYIK Last Updated:2025/05/07 Views:

requestsThis article will discuss and implement different curl commands using the module in Python .


requestsInstalling modules in Python

Python provides us with requeststhe module to execute curl command. Install it in Python 3 using Pip3 by running the following command in the bash terminal.

pip3 install requests

For previous versions of Python, install Requests module using Pip by executing the following command.

pip install requests

The next section will implement all the curl methods in Python one by one.

This tutorial will execute commands by sending requests to the Dummy Rest API, which is a dummy API that responds to curl commands. The data returned by the curl command contains a fake social media platform with different users, posts, albums, photos, and more.


requestsDifferent Curl commands using module in Python

Because we need to perform different actions when interacting with the server, there are specific curl commands for each task.

GetImplementing Curl command in Python using Requests module

We use Getthe curl method to request information from the server. Examples of this are any read-only operations like clicking on a web page, streaming a video, etc.

We can use requests.get()the method, which accepts Getthe URL of the method as its input parameter and returns an object requests.Responseof type Response.

example:

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.get(api_link)
print("The response is:", output)
print("Data type of response is:", type(output))

Output:

The response is: <Response [200]>
Data type of response is: <class 'requests.models.Response'>

Each returned Responseobject has specific properties like response code, headers, content etc. We can access it as follows.

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.get(api_link)
print("The header in the response is:")
print(output.headers)
print("The response code is:")
print(output.status_code)
print("The response url is:")
print(output.url)
print("The response content is:")
print(output.content)

Output:

The header in the response is:
{'Date': 'Wed, 23 Feb 2022 16:29:06 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '998', 'X-Ratelimit-Reset': '1645368134', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'max-age=43200', 'Pragma': 'no-cache', 'Expires': '-1', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"116-jnDuMpjju89+9j7e0BqkdFsVRjs"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', 'Age': '2817', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=gqOambHdiHjqe%2BfpyIj5A5LYTGm%2BONF4uN9kXU9%2ByYgYx%2BbU1xmnrgw8JJk4u5am5SZn%2F1xyvb%2By4zB2zNkuT%2F1thH%2Bx8xr82N50ljyZwfBS3H6n46N%2B33UdXGh2La0Oa9%2FkhbLOzr2fYmzednU6"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6e21d4c3cfc06eec-BOM', 'Content-Encoding': 'gzip', 'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'}
The response code is:
200
The response URL is:
https://jsonplaceholder.typicode.com/posts/2
The response content is:
b'{\n  "userId": 1,\n  "id": 2,\n  "title": "qui est esse",\n  "body": "est rerum tempore vitae\\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\\nqui aperiam non debitis possimus qui neque nisi nulla"\n}'

To print the text in the response, we can use the property Responseof the object text.

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.get(api_link)
print("The text in the response is:")
print(output.text)

Output:

The text in the response is:
{
  "userId": 1,
  "id": 2,
  "title": "qui est esse",
  "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}

We can also use print method's response json()in JSON format .get()

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.get(api_link)
print("The json content in the response is:")
print(output.json())

Output:

The json content in the response is:
{'userId': 1, 'id': 2, 'title': 'qui est esse', 'body': 'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla'}

requestsImplementing PostCurl command in Python using module

We can Postsend data to the server using the command, treating it as an insert operation in a collection. Here, we do not need to specify where the data should be stored.

PostExamples of methods include creating a user account on a social media platform, posting a question on StackOverflow, etc.

To do this, we can use requests.post()the method.

post()The method takes Requestthe URL of the new object as its first input parameter. We can pass objects such as dictionaries, lists of tuples, or JSON objects as input parameters to the data parameter.

We can send headers using headers parameter, JSON object using JSON parameter etc. The default value of data parameter is None.

After execution, post()the method sends a post request to the server and returns an object requests.Responseof data type Response.

example:

import requests as rq

data_object = {"userId": 111, "id": 123, "title": "Sample Title"}
api_link = "https://jsonplaceholder.typicode.com/posts/"
output = rq.post(api_link, data_object)
print("The response is:", output)
print("Data type of response is:", type(output))

Output:

The response is: <Response [201]>
Data type of response is: <class 'requests.models.Response'>

In the example, we used Postthe curl command in Python to create a new post record in the server's database.

In reality, since we are using a dummy REST API, no post is made to the server. However, the server simulates a process and returns a status code and relevant data indicating that post()the command has been executed.

Access the different properties of the object post()returned by the method Responseas shown below.

import requests as rq

data_object = {"userId": 111, "id": 123, "title": "Sample Title"}
api_link = "https://jsonplaceholder.typicode.com/posts/"
output = rq.post(api_link, data_object)
print("The header in the response is:")
print(output.headers)
print("The response code is:")
print(output.status_code)
print("The response url is:")
print(output.url)
print("The response content is:")
print(output.content)

Output:

The header in the response is:
{'Date': 'Wed, 23 Feb 2022 16:46:37 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '61', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '999', 'X-Ratelimit-Reset': '1645634849', 'Vary': 'Origin, X-HTTP-Method-Override, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '-1', 'Access-Control-Expose-Headers': 'Location', 'Location': 'http://jsonplaceholder.typicode.com/posts//101', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"3d-uGbtVxfcg580jWo4cMrgwUKWTZA"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'DYNAMIC', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=dpGflkwdx9n%2B3elhuPKogSNjzW5A1yBpla29W5VLk6YLUzQG2i53oQXEXbF2lxPbN0qsq%2BqC%2BXSpKxAbWqN36I5sTONqyblOz%2BQ5j8mYIGGQeuWI7KiU03Vwp8BTiGwqeOBES6DOGuU22peaa78J"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6e21ee68cbd92eb6-SIN', 'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'}
The response code is:
201
The response URL is:
https://jsonplaceholder.typicode.com/posts/
The response content is:
b'{\n  "userId": "111",\n  "id": 101,\n  "title": "Sample Title"\n}'

PutImplementing Curl command in Python using Requests module

We also use Putthe method to send data to the server, but we specify where the data goes. Examples include updating a profile on a social media platform, posting an answer to a StackOverflow question, etc.

To implement Putthe curl command, we can use put()the method, similar to post()the method.

After execution, it also returns an object requests.Responseof data type .Response

import requests as rq

data_object = {"userId": 1, "id": 2, "title": "updated title", "body": "updated body"}
api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.put(api_link, data_object)
print("The response is:", output)
print("Data type of response is:", type(output))

Output:

The response is: <Response [200]>
Data type of response is: <class 'requests.models.Response'>

We put()updated a post using the update method. Again, since we used a dummy REST API, the post was not updated on the server.

As shown below, we can print different properties of the object put()returned by the method .Response

import requests as rq

data_object = {"userId": 1, "id": 2, "title": "updated title", "body": "updated body"}
api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.put(api_link, data_object)
print("The header in the response is:")
print(output.headers)
print("The response code is:")
print(output.status_code)
print("The response url is:")
print(output.url)
print("The response content is:")
print(output.content)

Output:

The header in the response is:
{'Date': 'Wed, 23 Feb 2022 16:49:24 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '999', 'X-Ratelimit-Reset': '1645634969', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '-1', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"54-RFApzrEtwBFQ4y2DO/oLSTZrNnY"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'DYNAMIC', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=ad%2B%2FEAFK338xNieWtoBeSIPLc7VH015dF65QUBuE7AknX%2BKVHgzcoY7wCDpuExtug1w3zLMXq8mO%2FDVjAKEFyXe6RsgvvwEvtg8gP5elj7sDxXGDT6nXEqG7l6Q9XQ%2BY5J0SqzQIouNZ2gyo0J91"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6e21f27ed9ea563a-SIN', 'Content-Encoding': 'gzip', 'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'}
The response code is:
200
The response URL is:
https://jsonplaceholder.typicode.com/posts/2
The response content is:
b'{\n  "userId": "1",\n  "id": 2,\n  "title": "updated title",\n  "body": "updated body"\n}'

requestsImplementing DeleteCurl command in Python using module

As the name suggests, we use Deletethe method to delete the specified data from the server. DeleteExamples of methods include deleting personal information from a social media account, deleting answers to a StackOverflow question, etc.

To implement Deletethe curl command, we use requests.delete()the method.

delete()The curl method takes as input parameters the URL on which we have to perform Deletethe curl operation and other relevant data. It also returns an object requests.Responseof data type Response.

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.put(api_link)
print("The response is:", output)
print("Data type of response is:", type(output))

Output:

The response is: <Response [200]>
Data type of response is: <class 'requests.models.Response'>

ResponseUse the following code to print the different properties of the returned object.

import requests as rq

api_link = "https://jsonplaceholder.typicode.com/posts/2"
output = rq.put(api_link)
print("The header in the response is:")
print(output.headers)
print("The response code is:")
print(output.status_code)
print("The response url is:")
print(output.url)
print("The response content is:")
print(output.content)

Output:

The header in the response is:
{'Date': 'Wed, 23 Feb 2022 16:52:58 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '13', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '999', 'X-Ratelimit-Reset': '1645635209', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '-1', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"d-GUEcOn+YmHSF2tizNHXIHPjfR5k"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'DYNAMIC', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=WCIIO1n%2FtlmR6PYwsKbNmScEPP8ypXyY0du2MWE9cYjkX3Yjl1CD4m4XgJ%2FAdDYrPQxfyc%2B4b%2F1dn%2FbimsZi9sMn0s%2FocQdFGCulOadr%2FjMmM%2FN10STq3z7v5LklANYT%2BOwW6nZg5gYNFj8BY1Z3"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6e21f7b75ec884e9-BOM', 'alt-svc': 'h3=":443"; ma=86400, h3-29=":443"; ma=86400'}
The response code is:
200
The response URL is:
https://jsonplaceholder.typicode.com/posts/2
The response content is:
b'{\n  "id": 2\n}'

in conclusion

This article discusses the curl commands and requestsimplements them in Python using the module. The methods provided in the Requests module pycurlare slower than those provided in the module.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Implementing a Low-Pass Filter in Python

Publish Date:2025/05/07 Views:89 Category:Python

Low pass filter is a term in signal processing basics and is often used to filter signals to obtain more accurate results. This tutorial will discuss the low-pass filter and how to create and implement it in Python. A low-pass filter is use

Pretty Printing Dictionaries in Python

Publish Date:2025/05/07 Views:126 Category:Python

This tutorial will show you how to pretty print dictionaries in Python. Pretty printing means presenting some printed content in a more readable format or style. pprint() Pretty printing dictionaries in Python pprint is a Python module that

Writing logs to a file in Python

Publish Date:2025/05/06 Views:133 Category:Python

This tutorial will show you how to write logs to files in Python. Use the module in Python logging to write logs to files Logging is used to debug a program and find out what went wrong. logging The log module is used to log data to a file

Comparing two dates in Python

Publish Date:2025/05/06 Views:97 Category:Python

This tutorial explains how to compare two dates in Python. There are multiple ways to determine which date is greater, so the tutorial also lists different sample codes to illustrate the different methods. Comparing two dates in Python usin

Reload or unimport modules in Python

Publish Date:2025/05/06 Views:59 Category:Python

Modules allow us to store definitions of different functions and classes in Python files, which can then be used in other files. pandas , NumPy , scipy , Matplotlib are the most widely used modules in Python. We can also create our own modu

Pausing program execution in Python

Publish Date:2025/05/06 Views:157 Category:Python

This tutorial will demonstrate various ways to pause a program in Python. Pausing the execution of a program or application is used in different scenarios, such as when a program requires user input. We may also need to pause the program fo

Importing modules from a subdirectory in Python

Publish Date:2025/05/06 Views:191 Category:Python

This tutorial will explain various ways to import modules from subdirectories in Python. Suppose we have a file in a subdirectory of our project directory and we want to import this file and use its methods in our code. We can import files

Sleeping for a number of milliseconds in Python

Publish Date:2025/05/06 Views:124 Category:Python

In this tutorial, we will look at various ways to pause or suspend the execution of a program in Python for a given amount of time. Let's say we want to pause the execution of a program for a few seconds to let the user read instructions ab

Python Numpy.pad Function

Publish Date:2025/05/06 Views:104 Category:Python

In Python, we have NumPy the array module to create and use arrays. Arrays can have different sizes and dimensions. Padding is a useful method that can be used to compensate for the size of an array. We can mutate an array and add some padd

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial