Python Requests Example
Python requests is a library that allows you to send HTTP requests using Python. It is one of the most popular libraries for sending HTTP requests in Python. Here is an example of how to use Python requests.
Installation
You can install Python requests using pip:
pip install requests
Basic Usage
Here is an example of how to send a GET request using Python requests:
import requests
response = requests.get('https://api.example.com')
print(response.text)
This code sends a GET request to https://api.example.com and prints the response text.
POST Request
You can also send POST requests using Python requests. Here is an example:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com', data=payload)
print(response.text)
This code sends a POST request to https://api.example.com with the payload {'key1': 'value1', 'key2': 'value2'} and prints the response text.
Headers
You can also add headers to your requests using Python requests. Here is an example:
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get('https://api.example.com', headers=headers)
print(response.text)
This code sends a GET request to https://api.example.com with the User-Agent header set to a specific value.
Multiple Ways to Send Requests
Python requests provides multiple methods for sending HTTP requests, such as:
- requests.get()
- requests.post()
- requests.put()
- requests.patch()
- requests.delete()
You can use the appropriate method based on the type of request you want to send.
Syntax Highlighting
You can use the highlight.js library for syntax highlighting in your code blocks. Here is an example:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<pre><code class="python">
import requests
response = requests.get('https://api.example.com')
print(response.text)
</code></pre>
This code block uses the highlight.js library to highlight the Python code.