[Code] python call api example

The basic steps to call the api are as follows:

1. Import the requests library, which is a commonly used library for sending and processing http requests.
2. Create a request object, specify the requested url, method, parameters, header and other information.
3. Send the request and get the response object.
4. Check the status code, content, format and other information of the response.
5. If the response is in json format, you can use the json module to parse it into a python dictionary or list.

Here's a sample code that calls an API that gets the location of the International Space Station:

# 导入requests库
import requests
# 导入json库
import json

# 创建请求对象
url = "http://api.open-notify.org/iss-now.json"
method = "GET"
params = {
    
    }
headers = {
    
    }

# 发送请求,获取响应对象
response = requests.request(method, url, params=params, headers=headers)

# 检查响应状态码
if response.status_code == 200:
    print("请求成功")
else:
    print("请求失败")

# 检查响应内容
print(response.text)

# 检查响应格式
print(response.headers["Content-Type"])

# 如果响应是json格式,解析成python字典
if response.headers["Content-Type"] == "application/json":
    data = json.loads(response.text)
    print(data)

Guess you like

Origin blog.csdn.net/weixin_45392674/article/details/130315177