Python RESTful API framework: Eve Quick Start

Source: Internet
Author: User
Tags curl

Eve is a Python Rest API framework for publishing highly customizable, full-featured restful Web services that help you easily create and deploy APIs, translated from Eve's official website:
Http://python-eve.org/quickstart.html#database-interlude

Eve Quick Start:
Do you want to start? This page will provide a good introduction to Eve. Prior to this assumption:
You've already installed Eve. If you haven't, you can click on the installation page.
MongoDB has been installed.
And MongoDB has already run.
one of the smallest applications
One of the smallest Eve apps that looks like this:

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

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

DOMAIN = {‘people‘: {}}

It is then saved as settings.py and placed in the same folder as run.py.
This is Eve's profile, a standard Python module, this file tells Eve that your API contains an accessible resource, people.

Now you're ready to launch your API.

$ Runninghttp://127.0.0.1:5000/

Now you are 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 gotten a good response back, 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 provides API resource access information, and in our case, only one resource available for child, here is people.

Now try to request people:

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

This time we also get a _items table, _links relative to the resources being accessed, 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 because we have not specified any database details in settings.py, so Eve will seamlessly provide an empty resource when it is not possible to index the actual content of any people table, even if it does not exist, because we do not want to let the user of the API down (do not know what to translate into good ...). )。
Insert Database
Let's connect to the database by adding the following lines to setting.py:

# Let‘suseandoutdefaultto‘mongod‘localhost27017‘user‘user‘apitest‘

Because of the convenience of MongoDB, we do not really have to create a data table, in fact, we do not even need to create a database: Get request empty or nonexistent database is going to return the correct (k OK will get an empty set (table)); delete/patch/ The put gets the appropriate response (404 Not Found), and the POST request creates the database or table that you want. However, such an automatically managed database will perform poorly because of the lack of indexes and optimizations of any kind.
A more complex application
So far our APIs have been read-only, allowing us to perform crud (Create, read (Retrieve), update, and delete) operations in a comprehensive way:

# Enable Reads (GET), inserts (POST) andDELETE  forresources/collections# (ifYou omit this line, the API woulddefault  to[' GET '] andprovide#Read- onlyAccess toThe endpoint). Resource_methods = [' GET ',' POST ',' DELETE ']# Enable Reads (GET), edits (PATCH), Replacements (PUT) andDeletes of# Individual items (defaults to Read- onlyItem access). 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, which we will see shortly.
Since we allow editing, we also want to allow the data to be validated appropriately. Let's define a pattern for the people resource.

schema = {# Schema Definition, based on Cerberus grammar. Check The Cerberus Project# (https://github.com/nicolaiarocci/cerberus) for details.    ' FirstName ': {' type ':' String ',' minlength ':1,' maxlength ':Ten,    },' LastName ': {' type ':' String ',' minlength ':1,' maxlength ': the,' Required ': True,# talk on hard constraints! For the purpose of the demo# ' LastName 'is a API entry-point, so we need it to be unique.' Unique ': True,},# ' role 'is a list, and can only contain values from' allowed '.' role ': {' type ':' list ',' allowed ': ["Author","Contributor","Copy"],    },# an embedded' strongly-typed 'Dictionary.' Location ': {' type ':' Dict ',' schema ': {' Address ': {' type ':' String '},' City ': {' type ':' String '}        },    },' Born ': {' type ':' datetime ',    },}

For more information validation, see Data availability.

Now let's discuss the people we want to further customize the endpoint, and we want to:
Set the title of an item to person
Add an additional customization endpoint at/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 'Tag usedinchItem links. Defaults to the resource title minus # theFinal, plural' s '(Works fineinchMost cases and not for ' People ')' Item_title ':' person ', # BydefaultThe standard item Entry point isDefined as#'/people/<objectid> '. We leave it untouched, and we also enable a # additional Read-only entry point. This is the consumers can also perform # GET requests at'/people/<lastname> '.' Additional_lookup ': {' URL ':' Regex ("[\w]+") ',' field ':' LastName '}, # We choose toOverrideGlobal Cache-control directives for  ThisResource.' Cache_control ':' Max-age=10,must-revalidate ',' Cache_expires ':Ten, # Most global settings can is 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 the 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 can also update and delete items (but not the entire resource, as we have disabled). We can also perform 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 more examples of use.

PostScript:
All the examples and snippets are from live demo, 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 Quick 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.