python的接口样例
时间: 2023-10-12 09:14:31 浏览: 48
以下是一个简单的Python接口样例:
```python
import requests
def get_weather(city):
api_key = "your_api_key"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather = data["weather"][0]["description"]
temperature = data["main"]["temp"]
return f"The weather in {city} is {weather} with a temperature of {temperature} Kelvin."
else:
return "Unable to get weather information."
print(get_weather("London"))
```
该接口使用OpenWeatherMap API获取指定城市的天气信息,并返回一个字符串,包含城市、天气和温度。如果请求失败,则返回一个错误消息。
相关问题
python接口测试样例
当然,我可以给你一个简单的 Python 接口测试样例。下面是一个使用 `requests` 库发送 GET 请求的示例代码:
```python
import requests
def send_get_request(url):
try:
response = requests.get(url)
response.raise_for_status() # 抛出异常如果响应状态码不是 200
return response.json() # 将响应解析为 JSON 格式
except requests.exceptions.RequestException as e:
print("请求发生错误:", e)
# 示例使用
url = "https://api.example.com/users"
data = send_get_request(url)
print(data)
```
在这个示例中,我们首先导入 `requests` 库,然后定义了一个 `send_get_request` 函数,该函数接受一个 URL 参数,并发送 GET 请求。如果请求成功,函数将返回响应的 JSON 数据;则,将打印出错误信息。
你可以根据自己的需求修改该样例代码,例如添加请求头、发送 POST 请求等。希望这个样例对你有帮助!如果你有其他问题,请随时提问。
python调用POST请求接口代码样例
以下是一个使用 Python 发送 POST 请求的代码样例:
```python
import requests
url = "http://example.com/api"
data = {"key1": "value1", "key2": "value2"}
response = requests.post(url, data=data)
print(response.text)
```
在这个例子中,我们使用 `requests` 第三方库发送了一个 POST 请求到 `http://example.com/api`,并且将数据 `{"key1": "value1", "key2": "value2"}` 作为请求的主体发送。最终,我们使用 `response.text` 检查了接口返回的响应内容。