RESTful API
RESTful API is a resource-oriented programming, also called Representational State transfer (English: representational, Transfer, or rest).
Think that all the things on the network are resources, the operation of resources is nothing more than adding and deleting.
The traditional approach
For example, there is an asset page, the URL is www.example.com/asset
. To do this, you might use a different URL to differentiate:
www.example.com/addAsset
: Adding assets is generally the post method.
www.example.com/delAsset
: Delete an asset, typically the post method.
www.example.com/editAsset
: Modifying an asset is typically the post method.
www.example.com/showAsset
: Displays an asset, typically a GET method. may also be used www.example.com/asset
as a URL
The URLs here generally use verbs, which indicate an action.
Rules for RESTful APIs
The RESTful API uses a URL to refer to a resource, and since it is a resource, the word uses nouns. So this URL is www.example.com/asset
. Additions and deletions are implemented through this URL, through different methods to implement different approaches, commonly used are the following methods:
- GET (SELECT): Remove resources from the server (one or more items).
- POST (Create): Creates a new resource on the server.
- PUT (UPDATE): Updates the resource on the server (the client provides a full resource after the change).
- PATCH (UPDATE): Updates the resource on the server (the client provides changed properties).
- Delete: Deletes a resource from the server.
In Django, it is recommended to use CBV. Of course FBV is not.
RESTful API Design Guide
This article seems to be very good, worth reference: http://www.ruanyifeng.com/blog/2014/05/restful_api.html
Jsonresponse
Using the API will have many of the operations returned by the serialized data.
Before we had to return the serialized string to the front end, we tended to call the Json.dumps () method before returning the string to the front end with HttpResponse (). And since we're doing this every time, Django gave it to me. Encapsulates a new method for serializing and returning strings directly.
Jsonresponse This class is a subclass of the httprespon, which directly allows the dictionary to be serialized and returned to the front end.
>>> from django.http import JsonResponse>>> response = JsonResponse({‘foo‘: ‘bar‘})>>> response.content‘{"foo": "bar"}‘
The default is to pass in only one dictionary, and the data that the API returns should be a dictionary. However, if you must serialize a different type, such as a list, you can set the safe parameter:
>>> response = JsonResponse([1, 2, 3], safe=False)
If you want to customize the encoder, as with the JSON method, specify by the following parameters:
>>> response = JsonResponse(data, encoder=MyJSONEncoder)
Python Automation Development Learning-restful API