Application Programming Interfaces -- 1

来源:互联网 发布:滨州行知中学电话 编辑:程序博客网 时间:2024/06/05 02:26

照着书抄了一遍。

In recent years, there has been a trend in web applications to move more and more of business logic to the client side, producing an architecture that is known as Rich Internet Application(RIA). In RIAs, the server’s main function is to provide the client application with data retrival and storage services. In this model, the server becomes a web service or Application Programming Interfaces (API).

There are several protocols by which RIAs can communicate with a web service. Remote Procedure Call (RPC) protocols such as XML-RPC or its derivative Simplified Object Access Protocol (SOAP) were popular choices a few years ago. More recently, the Representional State Transfer (REST) architecture has emerged as the favorite for web applications due to it being built on the familiar model for the World Wide Web.

Flask is an ideal framework to build RESTful web services due to its lightweight nature. In the rest of the article, you will learn how to implement a Flask-based RESTful API.

Introduction to REST

Roy Fielding’s Ph.D. dissertation introduces the REST architectural style for web services by listing its six defining characteristics:

Client-Server
There must be a clear separation between the clients and the server.

Stateless
A client request must contain all the information that is necessary to carry it out.
The server must store any state about the client that persists from one request to the next.

Cache
Reponses from the server can be labeled as cacheable or noncacheable so that client(or intermediaries between clients and servers) can be use a cache for the optimization purposes.

Uniform Interface
The protocol by which clients access server resources must be consistent, well defined, and standardized. The commonly used uniform interface for REST web services is the HTTP protocol.

Layered System
Proxy server, caches, or gateways can be inserted between clients and servers as necessary to improve performance, reliability, and scalability.

Code-on-Demand
Clients can optionally download code from the server to the execute in their context.

Resources Are Everything

The concept of resources is core to the REST architectural style. In this context, a resource is an item of interest in the domain of the application. For example, in the blogging application, users, blog posts, and comments are all resources.

Each resource must have a unique URL that represents it. Contiuning with the blogging example, a blog post could be represented by the URL /api/posts/12345, where 12345 is a unique identifier for the post such as the post’s database primary key. The format or contents of the URL do not really matter; all that matters is that each resource URL uniquely identifies a resource.

A collection of all resources in a class also has an assigned URL. The URL for the collection of blog posts could be api/posts/ and the URL for the collection of all comments could be /api/comment/.

An API can also define collection URLs that represent logical subsets of all the resources in a class. For example, the collection of all comments in blog post 12345 could be represented by the URL /api/posts/12345/comments/. It is a common practice to define URLs that represent collections of resources with a trailing slash, as this gives them a “folder” representation.

Be aware that Flask applies special treatment to the routes that end with a slash. If a client requests a URL without a trailing slash and the only matching route has a slash at the end, then Flask will automatically respond with a redirect to the trailing slash URL. No redirects are issued for the reverse case.

Request Method

The client application sends requests to the server at the established resource URLs and uses the request method to indicate the desired operation. To obtain the list of variable blog posts in the blogging API the client would send a GET request to http://www.example.com/api/posts/, and to insert a new blog post it would send a POST request to the same URL, with the contents of the blog post in the request body. To retrieve blog post 12345 the client would send a GET request to http://www.example.com/api/posts/12345. Table 1 lists the request methods that are commonly used in RESTful APIa with their meanings.

Table 1. HTTP requests methods in RESTful APIsRequest methodTargetDescriptionHTTP status codeGETIndividual resource URLObtain the resource.200GETResource collection URLObtain the collection of resources(or one page from it if the server implements pagination)200POSTResource collection URLCreate a new resource and add it to the collection. The server chooses the URL of the resource and returns it in a Location header in the reponse.201PUTInvividual resource URLModify an existing resource. Alternatively this method can also be used to create a new resource when the client can choose the resource URL.200DELETEIndividual resource URLDelete a resource.200DELETEResource collection URLDelete all resources in the collection.200


The REST architure does not requir that all methods be implemented for a resource. If the client invokes a method that is not supported for a given resource, then a reponse with 405 status code for “Method Not Allowed” should be returned. Flask handles this error automatically.

Request and Response Bodies

Resources are sent back and forth between client and server in the bodies of requests and reponses, but REST does not specify the format to used to encode resources. The Content-Type header in requests and responses is used to indicate the format in which a resource is encoded in the body. The standard content negotiation mechanisms in the HTTP protocol can be used between client and server to agree on a format that both support.

The two formats commonly used with RESTful web services are JavaScript Object Notation (JSON) and Extensible Markup Language (XML). For web-based RIAs, JSON is attractive because of its close ties to JavaScript, the client-side scripting language used by web browers. Returning to the blog example API, a blog post resource could be represented in JSON as follows:

{    "url": "http://www.example.com/api/posts/12345",    "title": "Writing RESTful APIs in Python",    "author": "http:'//www.example.com/api/user/2",    "body": "... text of the article here ...",    "comments": "http://www.example.com/api/posts/12345/comments"}

Note how the url, author, and comments fields in the blog post above are fully qualified resource URLs. This is important because these URLs allow the client to discover new resources.

In a well-designed RESTful API, the client just knows a short list of top-level resource URLs and then discovers the rest from links included in responses, similar to how you can discover new web pages while browsing the Web by clicking on links that appear in pages that you know.

Versioning

In a traditional server-centric web application, the server has full control of the application. When an application is updated, installing the new version in the server enough to update all users because even the parts of the application that run in the user’s web brower are downloaded from the server.

The situation with RIAs and web services is more complicated, because often clients are developed independently of the server–maybe even by different people. Consider the case of an application where the RESTful web service is used by a variety of clients including web browsers and native smartphone clients. The web brower client can be updated in the server at any time, but the smartphone apps cannot be updated by force;the smartphone owner needs to allow the update to happen. Even if the smartphone owner is willing to update, it is not possible to time the deployment of the updated smartphone applications to all the apps stores to coincide exactly with the deployment of the new server.

For these reasons, web services need to be more tolerant than regular web applications and be able to work with old versions of its clients. A common way to adress this problem is to version the URLs handled by the web service. For example, the first release of the blogging web service could expose the collection of blog posts at /api/v1.0/posts/.

Including the web service version in the URL helps keeps old and new features organized so that the server can provide new features to new clients while contiuning to support old clients. An update to the blogging service could change the JSON format of blog posts and now expose blog posts as /api/v1.1/post/, while keeping the older JSON format for clients that connect to /api/v1.0/posts/. For a period of time, the server handles all the URLs in their v1.1 and v1.0 variations.

Although supporting multiple versions of the server can become a maintenance burden, there are situations in which this is the only way to allow the application to grow without causing problems to existing deployments.

RESTful Web Services with Flask

Flask makes it very easy to create RESTful web services. The familar route() decorator along with its methods optional argument can be used to declare the routes that handle the resource URLs exposed by the service. Working with JSON data is also simple, as JSON data included with a request is automatically exposed as a request.json Python dictionary and a reponse that needs to contain JSON can be easily generated from a Python dictionary using Flask’s jsonify() helper function.

The following sections show how Flasky can be extended with a RESTful web service that gives clients access to blog posts ans related resources.

原创粉丝点击