API introductory tutorial (python implementation)

What is API

  API, called Application Programming Interface in full, is an application programming interface that can be used to retrieve code and send data to a server that uses the code.

  When we want to receive data from the API, we need to make a request. The request is spread across the entire network. For example, when you visit this blog post, your web browser sends a request to the server, and the server responds with the content of the web page.

Send API request with python

  Install the requests library in python first (enter directly in Teriminal)

pip install requests

The first simple API request

  There are many different types of requests in the requests library. The most commonly used GET request is used to retrieve data. Since we will only retrieve data, our focus will be on issuing "get" requests.

  To issue a "GET" request, we use the requests.get() function, which is defined as follows:

help(requests.get)
Help on function get in module requests.api:

get(url, params=None, **kwargs)
    Sends a GET request.
    
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response

Among them, first pay attention to url urlThe input parameter u r l is the most important API interface.

  Now we access an API

response = requests.get("http://api.open-notify.org/this-api-doesnt-exist")
print(response.status_code)

# 404

You may be familiar with the status code "404", which is a status code returned by the server, indicating that the resource to be obtained does not exist on this server.

There are many other status codes:

·200:一切正常,结果已返回(如果有)。
·301:服务器将您重定向到其他端点。当公司切换域名或更改端点名称时,可能会发生这种情况。
·400:服务器认为您提出了错误的请求。当您没有正确发送数据时,可能会发生这种情况。
·401:服务器认为您未通过身份验证。许多API都需要登录证书,因此当您没有发送正确的凭据来访问API时就会发生这种情况。
·403:您尝试访问的资源被禁止:您没有查看该资源的正确权限。
·404:在服务器上找不到您尝试访问的资源。
·503:服务器尚未准备好处理请求。

GET to the real resource

  Usually, multiple APIs are provided on a specific server. Each of these APIs is commonly referred to as an endpoint. The first endpoint we will use is http://api.open-notify.org/astros.json, which returns data about astronauts currently in space.

response = requests.get("http://api.open-notify.org/astros.json")
print(response.status_code)

# 200

The return value is "200", indicating that everything is normal and the result has been returned.

But it should be noted that the returned format is in JSON form, let's take a look at output:

print(response.json())

#{'message': 'success', 'people': [{'name': 'Alexey Ovchinin', 'craft': 'ISS'}, {'name': 'Nick Hague', 'craft': 'ISS'}, {'name': 'Christina Koch', 'craft': 'ISS'}, {'name': 'Alexander Skvortsov', 'craft': 'ISS'}, {'name': 'Luca Parmitano', 'craft': 'ISS'}, {'name': 'Andrew Morgan', 'craft': 'ISS'}], 'number': 6}

The output format is conducive to the calculator to read, but it is not easy for us to observe the characteristics of this set of data, so we need to import the json module to process this JSON data.

import json

def jprint(obj):
    # create a formatted string of the Python JSON object
    text = json.dumps(obj, sort_keys=True, indent=4)
    print(text)

jprint(response.json())

The output is as follows:

{
    
    
    "message": "success",
    "number": 6,
    "people": [
        {
    
    
            "craft": "ISS",
            "name": "Alexey Ovchinin"
        },
        {
    
    
            "craft": "ISS",
            "name": "Nick Hague"
        },
        {
    
    
            "craft": "ISS",
            "name": "Christina Koch"
        },
        {
    
    
            "craft": "ISS",
            "name": "Alexander Skvortsov"
        },
        {
    
    
            "craft": "ISS",
            "name": "Luca Parmitano"
        },
        {
    
    
            "craft": "ISS",
            "name": "Andrew Morgan"
        }
    ]
}

In this way, it looks like a dictionary in python, it is easy to see what attributes the data has, and it is also convenient for further data processing.

The second important parameter-params

  In the previous GET function, in addition to entering the URL, there is another attribute that is params. Not all request conditions require params, but to request certain specific data, you need to give the server a parameter to return the data you want.

  For example, the endpoint http://api.open-notify.org/iss-pass.json. This endpoint tells us next time that the International Space Station will pass a given position on the earth. At this time, we have to enter the geographic location and have obtained the location of the space station.

parameters = {
    
    
    "lat": 40.71,
    "lon": -74
}

Give a latitude and longitude information in the form of a dictionary, and use GET to request the data again.

response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
jprint(response.json())

Data returned:

{
    
    
    "message": "success",
    "request": {
    
    
        "altitude": 100,
        "datetime": 1568062811,
        "latitude": 40.71,
        "longitude": -74.0,
        "passes": 5
    },
    "response": [
        {
    
    
            "duration": 395,
            "risetime": 1568082479
        },
        {
    
    
            "duration": 640,
            "risetime": 1568088118
        },
        {
    
    
            "duration": 614,
            "risetime": 1568093944
        },
        {
    
    
            "duration": 555,
            "risetime": 1568099831
        },
        {
    
    
            "duration": 595,
            "risetime": 1568105674
        }
    ]
}

But the above-mentioned time—risetime is a string of numbers, which seems difficult to understand. This time format is called timestamp or epoch . We can use the datetime library to convert to a time format we are familiar with.

First take out time:

risetimes = []

for d in pass_times:
    time = d['risetime']
    risetimes.append(time)

print(risetimes)

Then import the datetime library to convert:

from datetime import datetime

times = []

for rt in risetimes:
    time = datetime.fromtimestamp(rt)
    times.append(time)
    print(time)

The results are clear at a glance:

2019-09-09 21:27:59
2019-09-09 23:01:58
2019-09-10 00:39:04
2019-09-10 02:17:11
2019-09-10 03:54:34

Conclusion

  This article is just a simple tutorial. Later I will publish a new practical article on using python to access the Turing robot API, so stay tuned.

− − − − − − − − − − − − − − − − ---------------- - -
This article first appeared inzyairelu.cn
Welcome to my website to comment and discuss
personal mailbox [email protected]
- - - - - - - - - - - - - - - - -------- --------

Guess you like

Origin blog.csdn.net/weixin_42731543/article/details/103040753