程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python builds rest style interface API

編輯:Python

This article has participated in 「 New people's creative ceremony activities 」, Start the road of nuggets creation together


Identify resources

structure REST API when , The first step to take is to determine API Resources to be managed . These resources are usually described as plural nouns , Such as customersevents 、 or transactions . stay Web When different resources are identified in the service , You will build a list of nouns , Used to describe how users can API Different data managed in .

When doing this , Be sure to consider any nested resources . for example ,customers May have guests or sales May contain events . In defining API Interface , It would be helpful to establish these resource hierarchies .

Define your interface

determine Web After the resources in the service , You need to use these resources to define API Interface . Here are some of the services you may be using for payment processing API Some sample interfaces for resources found in :transactions

HTTP Method Interface terminal node describe GET/transactions Get transaction list .GET/transactions/<transaction_id> Get single transaction .POST/transactions Create a new transaction .PUT/transactions/<transaction_id> Update transaction .PATCH/transactions/<transaction_id> Partial update transactions .DELETE/transactions/<transaction_id> Delete transaction .

These six nodes cover Web In service transactions establish 、 Read 、 All actions required to update and delete .Web Each resource in the service will have a similar node list , Depending on what users can use API Actions performed .

Be careful : Nodes should not contain predicates . contrary , You should choose the appropriate HTTP Method to communicate the operation of the endpoint . for example , The following endpoint contains an unneeded predicate :

GET /getTransactions

here ,get It does not need to be included in the interface .HTTP Method has provided semantic meaning to the endpoint by indicating the operation . You can delete... From the interface :GET

GET /transactions

This interface contains only one plural noun ,HTTP GET Methods communicate actions .

Now let's take a look at the interface example of nested resources . ad locum , You will see guests Nested in resources events The next interface :

HTTP Method Interface terminal node describe GET/events/<event_id>/guests Get guest list .GET/events/<event_id>/guests/<guest_id> Get a single guest .POST/events/<event_id>/guests Create a new guest .PUT/events/<event_id>/guests/<guest_id> Update guests .PATCH/events/<event_id>/guests/<guest_id> Partially updated guests .DELETE/events/<event_id>/guests/<guest_id> Delete guest .

Use these interfaces , Can manage specific events in the system .guests

This is not the only way to define interfaces for nested resources . Some people prefer to use query strings to access nested resources . The query string allows you to follow HTTP Request to send other parameters together . In the following interfaces , Append query string guests To get specific information event_id

GET /guests?event_id=23

This node guests Any unreferenced given... Will be filtered out event_id . And API Many things in design are the same , You need to decide which method is best for your Web service .


Be careful : REST API It's unlikely to be here Web The service remains unchanged throughout its lifecycle . Resources will change , You need to update the interface node to reflect these changes . This is it.  API Version control place .API Version control allows you to modify API, Without worrying about breaking existing integrations .

There are various version control strategies . Choosing the right option depends on API The requirements of . Here are some of the most popular API Version control options :

  • URI version control
  • HTTP Header versioning
  • Query string version control
  • Media type version control

Whatever strategy you choose , Yes API Versioning is an important step to ensure that it can adapt to changing needs and support existing users .


Select the data exchange format

For formatting Web Two common options for service data are  XML  and JSON. Traditionally ,XML stay [SOAP] API It's very popular in , but JSON stay REST API More popular in China . To compare the two , Look at a format that is XML and JSON Sample resources for book.

Here is a Book formatted as XML The book of :

<?xml version="1.0" encoding="UTF-8" ?>
<book>
<title>Python Basics</title>
<page_count>635</page_count>
<pub_date>2021-03-16</pub_date>
<authors>
<author>
<name>David Amos</name>
</author>
<author>
<name>Joanna Jablonski</name>
</author>
<author>
<name>Dan Bader</name>
</author>
<author>
<name>Fletcher Heisler</name>
</author>
</authors>
<isbn13>978-1775093329</isbn13>
<genre>Education</genre>
</book>

XML Use a series of Elements Code the data . Each element has a start and end tag , The data is somewhere in between . Elements can be nested in other elements . You can see this above , Several of these tags are nested in .<author>``<authors>

Now? , have a look JSON Same as in :book

{
"title": "Python Basics",
"page_count": 635,
"pub_date": "2021-03-16",
"authors": [
{"name": "David Amos"},
{"name": "Joanna Jablonski"},
{"name": "Dan Bader"},
{"name": "Fletcher Heisler"}
],
"isbn13": "978-1775093329",
"genre": "Education"
}

JSON Store data in something like Python Dictionary key value alignment . And XML equally ,JSON Support for nesting data to any level , So you can model complex data .

JSON and XML In essence, it is no better than the other , but REST API Developers prefer JSON. When You will REST API And  React or  Vue  When the front-end frame is paired , Especially so .

The design responds successfully

After selecting the data format , The next step is to determine how to respond HTTP request . come from REST API All responses to should have a similar format , And include the correct HTTP The status code .

In this section , You will view management cars detailed list Assumptions API Some examples of HTTP Respond to . These examples will show you how to set up API Format of response . For the sake of clarity , You will see the original HTTP Requests and responses , Instead of using something like .requests

To start , Please check out GET Yes /cars Request , Where the following list is returned :

GET /cars HTTP/1.1
Host: api.example.com

this HTTP The request consists of four parts :

  1. GET  yes HTTP Method type .
  2. /cars  yes API Interface .
  3. HTTP/1.1  yes HTTP edition .
  4. host :api.example.com  yes API host .

GET

These four parts are your contribution to /cars send out GET Request everything you need . Now let's look at the response . this API Use JSON As a data exchange format :

HTTP/1.1 200 OK
Content-Type: application/json
...
[
{
"id": 1,
"make": "GMC",
"model": "1500 Club Coupe",
"year": 1998,
"vin": "1D7RV1GTXAS806941",
"color": "Red"
},
{
"id": 2,
"make": "Lamborghini",
"model":"Gallardo",
"year":2006,
"vin":"JN1BY1PR0FM736887",
"color":"Mauve"
},
{
"id": 3,
"make": "Chevrolet",
"model":"Monte Carlo",
"year":1996,
"vin":"1G4HP54K714224234",
"color":"Violet"
}
]

The API Return a response , It includes cars A list of . You know that due to the status code 200 OK Why , Response successful . The header of the response Content-Type Also set to application/json . This tells the user to parse the response into JSON.

Be careful : When you use real API when , You will see more HTTP header . These headers are in API There's a difference between , So they have been excluded from these examples .

Be sure to always set the correct header on the response Content-Type. If sent JSON,Content-Type Is set to application/json . If XML, Set it to application/xml. This header tells the user how to analyze the data .

You also want to include the appropriate status code in the response . For any successful request ,GET Should return 200 OK . This tells the user that their request has been processed as expected .

Let's look at the other one GET request , This time it's a car :

GET /cars/1 HTTP/1.1
Host: api.example.com

this HTTP Request to inquire about cars 1 Of API. Here is the response :

HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 1,
"make": "GMC",
"model": "1500 Club Coupe",
"year": 1998,
"vin": "1D7RV1GTXAS806941",
"color": "Red"
},

This response contains a single... With vehicle data JSON object . Because it is a single object , So you don't need to wrap it in a list . Same as the previous response , There is also a status code .200 OK

Be careful : Requests should never modify existing resources . If the request contains data , This data should be ignored , also API Unchanged resource should be returned .GET

POST

Next , View the request to add a new car :POST

POST /cars HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"make": "Nissan",
"model": "240SX",
"year": 1994,
"vin": "1N6AD0CU5AC961553",
"color": "Violet"
}

this POST Request to include the new vehicle in the request JSON. It will header Content-Type Set to application/json In order to API Know the content type of the request .API Will be taken from JSON Create a new car .

Here is the response :

HTTP/1.1 201 Created
Content-Type: application/json
{
"id": 4,
"make": "Nissan",
"model": "240SX",
"year": 1994,
"vin": "1N6AD0CU5AC961553",
"color": "Violet"
}

This response has a status code 200 OK,201 Created Used to inform the user that a new resource has been created .201 Created Make sure to use... For all successful requests instead of POST .

This response also includes a copy of the new vehicle id, It consists of API Generated id Please be sure to send back... In the response a, So that the user can modify the resource again .

Be careful : When users use POST or PUT or PATCH When modifying resources , It is important to always send back a copy of the resource . such , Users can see the changes they have made .

PUT

Now look at the request :PUT

PUT /cars/4 HTTP/1.1
Host: api.example.com
Content-Type: application/json
{ "make": "Buick", "model": "Lucerne", "year": 2006, "vin": "4T1BF3EK8AU335094", "color":"Maroon" } 

This request uses... From the previous request id Use PUT All new data update cars . As a reminder , Please update all fields on the resource with the new data . Here is the response :

HTTP/1.1 200 OK
Content-Type: application/json
{ "id": 4, "make": "Buick", "model": "Lucerne", "year": 2006, "vin": "4T1BF3EK8AU335094", "color":"Maroon" } 

The response includes... With new data car Copy of . Again , You always want PUT Send back the requested full resource . This also applies to PATCH request :

PATCH /cars/4 HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"vin": "VNKKTUD32FA050307",
"color": "Green"
}

PATCH Request to update only a portion of the resource . In the above request ,vin and color The field will be updated with the new value . Here is the response :

HTTP/1.1 200 OK
Content-Type: application/json
{ "id": 4, "make": "Buick", "model": "Lucerne", "year": 2006, "vin": "VNKKTUD32FA050307", "color": "Green" } 

Response includes car A complete copy of . As you can see , Only vin and color Field updated .

DELETE

Last , have a look REST API Upon receipt of DELETE How to respond to a request . The following is to delete :

HTTP/1.1 204 No Content

This response includes only the status code . This status code 204 No Content Tell the user that the operation is successful , But nothing is returned in the response . It makes sense , because car have been deleted . There is no reason to send a copy back in the response .

Design error response

Yes REST API It is always possible for a request to fail . It is best to define the appearance of the error response . These responses should include a description of the error and the corresponding status code . In this section , You will look at a few examples .

First , Please check the API Requests for resources that do not exist in :

GET /motorcycles HTTP/1.1
Host: api.example.com

here , The user to /motorcycles Send a nonexistent request .API The following response will be sent back :

HTTP/1.1 404 Not Found
Content-Type: application/json
...
{
"error": "The requested resource was not found."
}

This response includes a status code . besides , The response also contains a... With a descriptive error message JSON object . Providing a descriptive error message provides the user with more context about the error .

Now look at the error response when the user sends an invalid request :

POST /cars HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"make": "Nissan",
"year": 1994,
"color": "Violet"

this POST Request includes JSON, But the format is incorrect . It is missing the closing brace at the end (}).API This data will not be processed . The error response will inform the user of the following problems :

HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "This request was not properly formatted. Please send again."
}

This response includes a descriptive error message and a status code , Inform the user that they need to repair the request .

There are several other ways , Even if the request is in the correct format , It could be wrong . In the next example , User sends request , But it contains unsupported media types :POST

POST /cars HTTP/1.1
Host: api.example.com
Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8" ?>
<car>
<make>Nissan</make>
<model>240SX</model>
<year>1994</year>
<vin>1N6AD0CU5AC961553</vin>
<color>Violet</color>
</car>

In this request , The user sends XML, but API Support only JSON. The API The response method of is as follows :

HTTP/1.1 415 Unsupported Media Type
Content-Type: application/json
{
"error": "The application/xml mediatype is not supported."
}

This response includes a status code , To indicate that the request contains API Unsupported data format . This error code is meaningful for malformed data , But even if the format is correct, the data is invalid ?

In the next example , User sends request , But the contained data does not match the fields of other data :

POST /cars HTTP/1.1
Host: api.example.com
Content-Type: application/json
{ "make": "Nissan", "model": "240SX", "topSpeed": 120 "warrantyLength": 10 } 

In this request , The user to JSON add to topSpeed and warrantyLength Field .API These fields are not supported , So it will respond with an error message :

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": "Request had invalid or missing data."
}

This response includes a status code . This status code indicates that there is no problem with the request , But the data is invalid .REST API The incoming data needs to be verified . If the user sends data with the request , be API The data should be validated and the user notified of any errors .

Response request ( Whether successful or wrong ) yes REST API One of the most important jobs . If your API Intuitive and accurate response , It will be easier for users to surround your Web Services build applications . Fortunately, , Some excellent Python Web The framework abstracts the process HTTP The complexity of the request and the return response .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved