python的request调用get、post、put、delete接口实战

本文介绍了如何使用Python的requests库进行GET、POST、PUT和DELETE接口调用。首先讲解了GET接口的实现,包括定义URL和参数,并展示了请求成功的验证方式。接着,文章以相同的方式展示了POST接口的调用。最后提到PUT和DELETE接口的调用方法,只需将请求方法替换为request.put()和request.delete()。
摘要由CSDN通过智能技术生成

request库引用可以自行baidu搜索,点击+号搜索requests库 

get接口

请求接口一定要有URL,参数,所以我们要定义我们的接口url和参数,我这个接口只有一个必填参数

url = 'http://localhost:9090/com/getSku'
    params = {
        'id': 1
    }

接下来就是输出看看我们是否请求成功~

 status_code = res.status_code
    print(f'响应码是:{status_code}')
    text = res.text
    print(f'响应信息是字符串形式的:{text}')
    json1 = res.json()
    print(f'响应信息是json形式的:{json1}')

运行起来

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的二次封装的接口请求类: ```python import requests class ApiRequest: def __init__(self, base_url): self.base_url = base_url def get(self, path, params=None, headers=None): url = self.base_url + path response = requests.get(url, params=params, headers=headers) return response.json() def post(self, path, data=None, json=None, headers=None): url = self.base_url + path response = requests.post(url, data=data, json=json, headers=headers) return response.json() def put(self, path, data=None, json=None, headers=None): url = self.base_url + path response = requests.put(url, data=data, json=json, headers=headers) return response.json() def delete(self, path, headers=None): url = self.base_url + path response = requests.delete(url, headers=headers) return response.json() ``` 使用方法: ```python # 创建对象 api = ApiRequest('https://jsonplaceholder.typicode.com') # GET 请求 response = api.get('/posts') print(response) # POST 请求 data = {'title': 'foo', 'body': 'bar', 'userId': 1} response = api.post('/posts', json=data) print(response) # PUT 请求 data = {'title': 'foo', 'body': 'bar', 'userId': 1} response = api.put('/posts/1', json=data) print(response) # DELETE 请求 response = api.delete('/posts/1') print(response) ``` 在创建 ApiRequest 对象时,需要传入一个基础的 URL,然后就可以使用类中提供的 get、post、put 和 delete 方法进行相应的请求了。每个方法都可以传入不同的参数,比如 GET 请求可以传入 params 和 headers,POST 和 PUT 请求可以传入 data、json 和 headers。每个方法返回的都是响应的 JSON 数据,可以根据具体需求进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值