python rest
时间: 2023-12-07 22:39:43 浏览: 74
以下是使用Python进行REST API交互的基本步骤:
1.导入requests库
```python
import requests
```
2.使用requests库发送HTTP请求
```python
response = requests.get('https://api.example.com')
```
3.处理响应
```python
print(response.status_code) # 输出响应状态码
print(response.text) # 输出响应内容
```
4.发送带有参数的请求
```python
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://api.example.com', params=payload)
```
5.发送带有请求头的请求
```python
headers = {'Authorization': 'Bearer mytoken'}
response = requests.get('https://api.example.com', headers=headers)
```
6.发送POST请求
```python
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com', data=payload)
```
阅读全文