Web API first experience - Python & easy language

      There are many API interfaces on the Internet, as long as a simple call can get the information we want, such as weather forecast, daily sentence and so on. Including some coupon grabbing activities, there are generally APIs that can be called directly.

      The first time I called my own API function should be in the Tencent cloud function, I wrote some broken code, set up the API gateway, and then I can use the browser to call and return the data with one click, which is quite fun.

      This time, I will learn more about it and try to build a WebApi service by myself.

01 | What is WebApi

      ASP.NET Web API is a framework for easily building HTTP services that can be accessed by a variety of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

      WebApi can be regarded as one of the Asp.Net project types, other project types such as the well-known WebForm project, Windows Form project, console application, etc.

      The biggest advantage of WebApi-type projects is that developers no longer have to worry about the serialization and deserialization of data transmitted between the client and server, because WebApi is strongly typed and can be serialized and deserialized automatically. The most important thing about Web API is that it can build services for various clients.

02 |  HTTP request method

The HTTP/1.1 protocol defines eight request methods to operate specified resources in different ways:

1. GET 

    Request the specified page information and return the entity body. It is used to obtain data from the server, and should not have any operation or influence on the server.

2. POST 

    Submit data to a specified resource to process a request (such as submitting a form or uploading a file). Data is included in the request body. POST requests may result in the creation of new resources and/or the modification of existing resources, with server-side effects.

3. PUT 

    The data transmitted from the client to the server replaces the content of the specified document, which means it is used to update a piece of data to the server and affect the server (it is also possible to create a new piece of data but this is not recommended).

4. DELETE 

    Request the server to delete the specified page, which will affect the server side.

5. HEAD 

    Similar to a GET request, except that there is no specific content in the returned response, which is used to obtain the header

6. OPTIONS 

    Allows clients to view server performance.

7. CONNECT 

    Reserved in the HTTP/1.1 protocol for proxy servers that can pipe connections into.

8. TRACE 

    Echoes the requests received by the server, mainly for testing or diagnosis.

      In this way, the first four request methods can just correspond to querying, adding, modifying, and deleting data. This is also recommended for WebApi. In the WebApi project, what we request is no longer a specific page, but a method in each controller. The Get type request is sent to the method starting with Get for processing, and the Post type request is sent to the method starting with Post for processing. The same is true for Put and Delete.

It is also possible to have several methods starting with Get. At this time, how to distinguish which method to execute? This depends on the incoming parameters of the methods at the beginning of Get, which can be distinguished in the code later.

03 | Python practice - FastAPI

      FastAPI is a modern, fast (high-performance) web framework for building APIs, using Python 3.6+ and based on standard Python type hints. Key Features:

Fast: Extremely performant alongside NodeJS and Go (thanks to Starlette and Pydantic), one of the fastest Python web frameworks.

         Use Python to write a simple code. First, the pip uvicorn and fastapi libraries are divided into two files. One file name is arbitrary, and its function is to start the service, referred to as the A file; the other is the api function code, referred to as the B file. A file code is as follows:

import uvicorn


if __name__ == '__main__':
    uvicorn.run(app='webapi:app', host='127.0.0.1', port=3000, reload=True)

In the code, webapi:app is the file name and service name of the B file, so the file name of the B file is webapi.py, and the name of the service object inside is app, and the IP address and port are set. The code of the B file is as follows:

from fastapi import FastAPI
import time,requests
app = FastAPI()


@app.get("/")
def info():
    return {"key": "欢迎关注【偶尔敲代码】"}


@app.get("/time")
def info():
    t = int(time.time())
    return {"time": str(t)}


#
@app.get("/yy")
def info():
    r = requests.get("https://apis.jxcxin.cn/api/yiyan?type=json")
    print(r)
    return r.text

The code of file B defines 3 api functions, namely "/", "/time" and "/yy".

Running the two files of AB is equivalent to starting the webapi service. At this time, combined with the IP address and port defined in our A file, directly access it on the browser: http://127.0.0.1:3000

The "/" function in the api can be triggered, and the result will be returned according to the settings in the B code.

5382edf14fbda2c3e8887ba1e9b228c2.png

Access http://127.0.0.1:3000/time directly on the browser to trigger the "/time" function in the API:

62ee77af3e44a1242bcd5167b3ad2e78.png

Access http://127.0.0.1:3000/yy directly on the browser to trigger the "/yy" function in the API:

5a3d30f71337f279ec611f6f49877fff.png

After debugging, deploy the above file on the server, modify the corresponding IP address to the public IP of the server, and open the corresponding port number to realize access.

04 | Easy language practice - WebAPI framework

        This is a WebAPI framework I found on the Internet. I just need to write plug-ins for related API functions, which means the same as the Python B file above, which is quite convenient. The function is probably like this. The server runs the framework, then loads its own plug-in, and defines its own calling method in the plug-in.

2fada0a355fc0194f0dc69d7eeb4e4dc.png

Summarize:

1. WebApi is very convenient for cross-platform, as long as you can call http commands;

2. You need to have your own server if you build it yourself

- End -

More exciting articles

Click on the business card below to follow【Occasionally type code】

Guess you like

Origin blog.csdn.net/a18065597272/article/details/129606104