python使⽤api_⽤python构建api的正确⽅法
python 使⽤api
How can we set up a way to communicate from one software instance to another? It sounds simple, and — to be completely honest — it is.
^ h我们流可以设置⽅式,从⼀个软件实例传达给别⼈呢? 听起来很简单,⽽且-坦⽩地说-确实如此。
All we need is an API.
我们需要的只是⼀个API。
An API (Application Programming Interface) is a simple interface that defines the types of requests (demands/questions, etc.) that can be made, how they are made, and how they are processed.
API(应⽤程序编程接⼝)是⼀个简单的接⼝,它定义了可以进⾏的请求类型(需求/问题等),如何进⾏以及如何处理。
In our case, we will be building an API that allows us to send a range of GET/POST/PUT/PATCH/DELE
TE requests (more on this later), to different endpoints, and return or modify data connected to our API.
在我们的案例中,我们将构建⼀个API,该API允许我们向不同的端点发送⼀系列GET / POST / PUT / PATCH / DELETE请求(稍后会详细介绍),并返回或修改连接到我们API的数据。
We will be using the Flask framework to create our API and Postman to test it. In short, we will cover:
我们将使⽤Flask框架创建我们的API,并使⽤Postman对其进⾏测试。 简⽽⾔之,我们将介绍:
> Setup
- Our Toy Data
- Initialize a Flask API
- Endpoints
- Running a Local Server> Writing Our API
- GET
- POST
- 401 Unauthorized
- PUT
- DELETE
- Users Class (summary)> That's It!
建⽴ (Setup)
Our API will contain two endpoints, users and locations. The former will allow access to our registered user's details, whereas the latter will include a list of cafe locations.
我们的API将包含两个终结点, users和locations 。 前者将允许访问我们注册⽤户的详细信息,⽽后者将包括咖啡馆位置列表。
The hypothetical use-case here is of a multi-million cafe bookmarking app, where users open the app and bookmark their favorite cafe’s — like Google Maps, but not useful.
此处假设的⽤例是数百万个咖啡馆的书签应⽤程序,⽤户可以在其中打开该应⽤程序并为⾃⼰喜欢的咖啡馆添加书签,例如Google Maps,但没有⽤。
我们的玩具数据 (Our Toy Data)
For the sake of simplicity, we are going to store this data in two local CSV files. In reality, you probably want to take a look at something like MongoDB or Google Firebase.
为了简单起见,我们将把这些数据存储在两个本地CSV⽂件中。 实际上,您可能想看看MongoDB或Google Firebase之类的东西。
Our CSV files look like this:
我们的CSV⽂件如下所⽰:
. Image by Author. ⽤户数据。 图⽚由作者提供。
. Image by Author. 。 图⽚由作者提供。
You can download , and .
您可以下载下载 。
初始化Flask API (Initialize a Flask API)
Now to our Python script, we need to import modules and initialize our API, like so:
现在到我们的Python脚本,我们需要导⼊模块并初始化我们的API,如下所⽰:
from flask import Flask
from flask_restful import Resource, Api, reqparse
import pandas as pdpython新手代码userid
import astapp = Flask(__name__)
api = Api(app)
终点 (Endpoints)
As we already touched on, our API will have two endpoints, users and locations.
正如我们已经谈到的那样,我们的API将具有两个端点, users和locations 。
The result of this is — if our API was located at www.api, communication with the Users class would be provided at www.api/users and Locations at
这样做的结果是-如果我们的API是位于www.api ,与通信Users类将在提供www.api /users和Locations在
To create an endpoint, we define a Python class (with any name you want) and connect it to our desi
red endpoint with api.add_resource, like this:
要创建端点,我们定义⼀个Python类(使⽤您想要的任何名称),然后使⽤api.add_resource将其连接到所需的端点,如下所⽰:
class Users(Resource):
# methods go here
pass
api.add_resource(Users, '/users')  # '/users' is our entry point
Flask needs to know that this class is an endpoint for our API, and so we pass Resource in with the class definition.
Flask需要知道此类是我们API的终结点,因此我们将Resource与类定义⼀起传⼊。
Inside the class, we include our HTTP methods (GET, POST, DELETE, etc.).
在类内部,我们包含我们的HTTP⽅法(GET,POST,DELETE等)。
Finally, we link our Users class with the /users endpoint using api.add_resource.
最后,我们使⽤api.add_resource将Users类与/users端点api.add_resource 。
Because we want two endpoints, we replicate the logic:
因为我们需要两个端点,所以我们复制逻辑:
class Users(Resource):
# methods go here
pass
class Locations(Resource):
# methods go here
pass
api.add_resource(Users, '/users')  # '/users' is our entry point for Users
api.add_resource(Locations, '/locations')  # and '/locations' is our entry point for Locations
运⾏本地服务器 (Running a Local Server)
Finally, when we write out our API, we need to test it!
最后,当我们写出我们的API时,我们需要对其进⾏测试!
To do this, we need to host our API, which we can do locally by adding app.run to the end of our script like this:
为此,我们需要托管我们的API,我们可以在本地通过将app.run添加到脚本末尾来进⾏本地化,如下所⽰:
if __name__ == '__main__':
app.run()  # run our Flask app
Now, when we run our script, we should see something like this:
现在,当我们运⾏脚本时,我们应该看到如下所⽰:
Initialization of our localhost server. Image by Author.
初始化我们的本地主机服务器。 图⽚由作者提供。
Once our server is setup, we can test our API as we build it using Postman, if you haven’t used it before it is the de-facto standard for API testing. And, don’t worry — it’s incredibly simple to use — download Postman from .
设置好服务器后,如果您在使⽤Postman构建API的事实上的标准之前还没有使⽤过它,就可以对其进⾏测试。 ⽽且,不⽤担⼼-使⽤起来⾮常简单-从下载Postman。
Before going ahead, you can find the full script that we will be building . If you’re not sure where a code snippet should go, check there!
在继续之前,您可以到我们将在构建的完整脚本。 如果不确定代码⽚段应该放在哪⾥,请检查那⾥!
编写API⽅法 (Writing API Methods)
Inside each of our classes, we keep our HTTP methods, GET, POST, and DELETE.
在每个类中,我们保留HTTP⽅法GET,POST和DELETE。
To create a GET method, we use def get(self). POST and DELETE follow the same pattern.
要创建GET⽅法,我们使⽤def get(self) 。 POST和DELETE遵循相同的模式。
得到 (GET)
The GET method is the simplest. We return all data stored in users.csv wrapped inside a dictionary, like so:
GET⽅法是最简单的。 我们返回存储在字典中的users.csv存储的所有数据,如下所⽰:
class Users(Resources):
def get(self):
data = pd.read_csv('users.csv')  # read CSV
data = _dict()  # convert dataframe to dictionary
return {'data': data}, 200  # return data and 200 OK code
We can then run the script to initialize our API, open Postman and send a GET request to our localhost address (typically )—this is our API entry point.
然后,我们可以运⾏脚本来初始化我们的API,打开Postman并将GET请求发送到我们的本地主机地址(通常为 ),这是我们的API ⼊⼝点。
How to send a GET request to our API. Image by Author.
如何将GET请求发送到我们的API。 图⽚由作者提供。
To send a GET request to our API in Postman we:
要将GET请求发送到Postman中的API,我们:
1. Select GET from the dropdown
从下拉列表中选择GET
2. Type the entry point of our API instance + /users (the endpoint)
输⼊我们的API实例+ /users的⼊⼝点( 端点 )
3. Hit Send
点击发送
4. Check the status code returned by our API (we should see 200 OK)
检查我们的API返回的状态码(我们应该看到200 OK )
5. View our API’s response, which is users.csv in JSON (like a dictionary) format
查看我们的API响应,即JSON (如字典)格式的users.csv
开机⾃检 (POST)
The POST method allows us to add records to our data. In this case, we will take arguments for usedId, name, and city.
POST⽅法允许我们将记录添加到数据中。 在这种情况下,我们将使⽤usedId , name和city 。
These arguments are passed to our API endpoint as URL parameters, which look like this:
这些参数作为URL参数传递到我们的API端点,如下所⽰:
Rock&city=Los Angeles
We can specify the required parameters, and then parse the values provided using reqparse — like this:
我们可以指定所需的参数,然后使⽤reqparse解析提供的值,如下所⽰:
parser = reqparse.RequestParser()  # initialize
parser.add_argument('userId', required=True)  # add arguments
parser.add_argument('name', required=True)
parser.add_argument('city', required=True)
args = parser.parse_args()  # parse arguments to dictionary
Let’s break our parser code down:
让我们分解⼀下解析器代码:
We initialize our parser with .RequestParser().
我们使⽤.RequestParser()初始化解析器。
Add our arguments with .add_argument([arg_name], required) — note that required=True means that the argument is required in the request. Alternatively, we can add optional arguments with required=False.
使⽤.add_argument([arg_name], required)添加参数—请注意, required=True表⽰请求中的参数是必需的。 另外,我们可以添加带有required=False可选参数。