Tutorials for writing web APIs in Python

Source: Internet
Author: User
Tags representational state transfer
Since Dr. Roy Fielding introduced the rest (representational state Transfer)-style software architecture pattern in his doctoral dissertation in 2000, rest has largely quickly replaced the complex and bulky soap as a web The standard of the API.

What is Web API?

If we want to get a blog, enter http://localhost:9000/blog/123, we can see the ID 123 blog page, but this result is an HTML page, it also contains the blog data and blog display two parts. For the user, reading is not a problem, but if the machine reads, it is difficult to parse out the data from the HTML blog.

If a URL returns not HTML, but the data that the machine can parse directly, the URL can be viewed as a web API. For example, read http://localhost:9000/api/blogs/123, if can directly return the data of the blog, then the machine can be read directly.

Rest is a pattern of designing APIs. The most commonly used data format is JSON. Because JSON can be read directly by JavaScript, the rest-style API written in JSON format is simple, easy to read, and easy to use.

What are the benefits of writing an API? Because the API is all about the functionality of the Web app, so through the API operation data, can greatly isolate the front-end and back-end code, so that the back-end code is easy to test, the front-end code is easier to write.

An API is also a processing function of a URL, we want to be able to directly through a @api to the function into a JSON-formatted rest API, so that the acquisition of registered users can be implemented with an API as follows:

@api @get ('/api/users ') def api_get_users (): Users  = User.find_by (' ORDER by created_at desc ')  # hides the user's password:  For u in users:    U.password = ' ****** '  return dict (users=users)

So, @api this decorator as long as it's written, you can turn any URL processing function into an API call.

Create a new apis.py, write @api is responsible for serializing the function's return result to JSON:

def API (func):  @functools. Wraps (func)  def _wrapper (*args, **kw):    try:      r = Json.dumps (func (*args, * * kw))    except Apierror, e:      r = Json.dumps (Dict (Error=e.error, Data=e.data, message=e.message))    except Exception, E:      r = Json.dumps (Dict (error= ' Internalerror ', data=e.__class__.__name__, message=e.message))    Ctx.response.content_type = ' Application/json '    return r  return _wrapper

@api need to handle the error. We define a apierror, which means that there is a logic error in the API call (for example, the user does not exist), the other error is considered a bug, and the wrong code returned is internalerror.

When the client invokes the API, the API call must be distinguished by the error code to be successful. The error code is used to tell the caller why the error occurred. Many APIs use an integer to represent the error code, which makes it difficult to maintain the error code, and the client gets the error code and needs to look up the error message. A better way is to use a string to represent the error code, and you can guess the cause of the error without looking at the document.

You can test the API directly in the browser, for example, by entering Http://localhost:9000/api/users, you can see the JSON returned:

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.