Python RESTful API framework: Eve Fast Start

Source: Internet
Author: User

Eve is a Python rest API framework. Used to advertise highly customizable, full-featured restful Web services. To help you easily create and deploy APIs, this article is translated from Eve's official site:
Http://python-eve.org/quickstart.html#database-interlude

Eve High Speed entry:
Do you want to start? This page will provide a very good introduction to Eve. Prior to this assumption:
You've already installed Eve.

If you are not yet, you can click on the installation page.
MongoDB has been installed.
And MongoDB is already running.


one of the smallest applications
One of the smallest Eve apps. It looks like this:

fromimport Eveapp = Eve()if‘__main__‘:    app.run()

Then save as run.py, and then create a new document that includes the contents:

DOMAIN = {‘people‘: {}}

Then save as settings.py. and put it in the same directory as run.py.
This is Eve's configuration file, a standard Python module that tells Eve that your API includes an accessible resource. People.

Now you are ready to launch your API.

$ Runninghttp://127.0.0.1:5000/

Now you're ready to use this API:

-i http://127.0.0.1:5000HTTP/1.0200 OKContent-Type: application/jsonContent-Length82Server: Eve/0.0.5-dev Werkzeug/0.8.3 Python/2.7.3Date27201316:06:44 GMT

Congratulations. Your GET request has been returned with a very good response. Let's take a look at this payload:

{    "_links{        "child": [            {                "href": "people",                "title": "people"            }        ]    }}

The API access point follows the Hateoas (Hypermedia as a state application engine) principle and the provision of API resource interview information, in our sample just provides a resource available to child, here is people.

Now try to request people:

$ http://127.0.0.1:5000/people
{"_items ": [] ," _links  ": {" self ": {"href ":  "people"  , "title ": 
      
        "people"  
      } , "parent ": {"href ": "/" ," title  ": " Home " } } }  

This time we also got a _items table, _links's relative resources, so you get the parent Resource Link (home page) and the resource itself.

By default, Eve's APIs are read-only:

$ curl -X DELETE http://127.0.0.1:5000/people<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><title>405 Method Not Allowed</title><h1>Method Not Allowed</h1><p>The method DELETE is not allowed for the requested URL.</p>

This is due to the fact that we have not specified any database details in settings.py, so Eve will seamlessly provide an empty resource when it cannot be indexed to whatever the actual contents of the People table are (or may not exist). Because we do not want to let the user of the API down (do not know what to translate into what good ...) )。
Insert Database
Let's connect to the database by adding the following lines to setting.py:

# 依据编辑须要,让我们使用本地mongod实例# 须要注意的是MONGO_HOST 和 MONGO_PORT非常有可能会无效。由于默认存在本地系统的值。‘localhost‘27017‘user‘‘user‘‘apitest‘

Because of the convenience of MongoDB, we do not need to actually create a data table. In fact, we don't even have to create a database: A GET request for an empty or nonexistent database is returned correctly (a $ ok will get an empty set (table)); Delete/patch/put will get an appropriate response (404 Not Found), The POST request creates the database or table that you want.

However, this self-managed database will run poorly due to the lack of indexes and optimizations in whatever form.


a more complex application
Our API is read-only until now. Let's get a full-fledged crud (Add (Create), read (Retrieve) (again get data), Updates (update), and delete) operations:

# 授权资源、数据库  读 (GET), 插入 (POST) and 删除 DELETE# (假设你省略这行, API将默认是 [‘GET‘] 和 提供仅仅读权限訪问端点).# RESOURCE资源。METHODS方法RESOURCE_METHODS = [‘GET‘‘POST‘‘DELETE‘]# 同意 读 (GET), 编辑 (PATCH), 替换 (PUT) 和删除 个人项目 items  (默认訪问项目是仅仅读).# ITEM 项目ITEM_METHODS = [‘GET‘‘PATCH‘‘PUT‘‘DELETE‘]

When a method in the Item_methods list authorizes a project endpoint (/people/), the method in the Resource_methods table authorizes the resource endpoint (/people).

All settings will have a global scope and make all endpoints valid. However, you can also enable or disable the HTTP method level for a single endpoint. We can see it very quickly.


As we agreed to edit, we also wanted the data to be properly validated.

Let's define a pattern for the people resource.

schema = {# Schema definitions, based on the Cerberus syntax. Verify the details of the Cerberus project in# (https://github.com/nicolaiarocci/cerberus).     ' FirstName ': {' type ':' String ',' minlength ':1,' maxlength ':Ten,    },' LastName ': {' type ':' String ',' minlength ':1,' maxlength ': the,' Required ': True,# The purpose of this demo is to discuss hard constraints# ' LastName 'is an API entry tag, so we need it to be unique.' Unique ': True,},# ' role 'is a table. And can only be a value in the allowed' role ': {' type ':' list ',' allowed ': ["Author","Contributor","Copy"],    },# A dictionary of embedded fixed types.' Location ': {' type ':' Dict ',' schema ': {' Address ': {' type ':' String '},' City ': {' type ':' String '}        },    },' Born ': {' type ':' datetime ',    },}

A lot of other information validation please look at the data validity.

Now let's discuss the people that we want to further customize the endpoint. We want to:
Set the title of an item to person
Add an additional self-defining item endpoint in/people/
Overriding the default cache control directives
Disable Delete for people endpoint (set global variable)

Here is a complete demonstration of the definition of people in the setting.py file update:

people = { # ‘title‘用于项目链接。

默认资源标题减去最后 复数 ‘s‘ (在大部分情况下工作正常。而不是‘people’) ‘item_title‘: ‘person‘, # 依据标准项目接入点是定义成‘/people/<ObjectId>‘。 #. 我们让它不可更改 和我们也启动一个额外的仅仅读接入点 。这种方法也能让消费者运行GET请求‘/people/<lastname>‘。 ‘additional_lookup‘: { ‘url‘: ‘regex("[\w]+")‘, ‘field‘: ‘lastname‘ }, # 我们决定对这个资源覆盖全局变量缓存控制准则。

‘cache_control‘: ‘max-age=10,must-revalidate‘, ‘cache_expires‘: 10, # most global settings can be overridden at resource level ‘resource_methods‘: [‘GET‘, ‘POST‘], ‘schema‘: schema}

Finally we update the domain definition:

DOMAIN = {    ‘people‘: people,}

Save setting.py and start run.py.

Now we can insert a document at the people endpoint:

‘[{"firstname": "barack", "lastname": "obama"}, {"firstname": "mitt", "lastname": "romney"}]‘‘Content-Type: application/json‘  http://127.0.0.1:5000/peopleHTTP/1.0201 OK

We are also able to update and delete items (but not the entire resource, as we have disabled).

We can also run a GET request to get this new LastName endpoint:

$ curl -i http://127.0.0.1:5000/people/obamaHTTP/1.020021201216:04:56‘max-age=10,must-revalidate‘10...
{    "FirstName":"Barack",    "LastName":"Obama",    "_id":"50acfba938345b0978fccad7" "  updated": "Wed," 16:04:56 GMT "     ,    "created":"Wed, 16:04:56 GMT",    "_links":{        " Self":{"href": "People/50acfba938345b0978fccad7", "title": "Person"},        "Parent":{"href": "/", "title": "Home"},        "Collection":{"href": "People", "title": "People"}}}

The cache guidelines and project headings meet our new settings. See product Features for a complete list of features and many other examples of using demos.

PostScript:
All of the samples and code snippets are from live demo. This is a full-featured API that you can use to your own experiments and live instances or local (you can also use an instance app to populate or reset the database).

Python RESTful API framework: Eve Fast Start

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.