杰瑞科技汇

Python RESTful Eve 如何快速上手?

Of course! Here is a comprehensive guide to building RESTful APIs with Python using the Eve framework.

Python RESTful Eve 如何快速上手?-图1
(图片来源网络,侵删)

What is Eve?

Eve is an open-source Python REST API framework designed for rapid development. It's built on top of other popular Python libraries, most notably Flask and MongoDB.

The key philosophy of Eve is "batteries-included". It aims to provide a fully-featured, production-ready REST API with minimal code from the developer. Instead of writing endpoint logic, you define your data resources and their structure, and Eve handles the REST endpoints, validation, authentication, caching, and more.


Why Choose Eve?

  • Rapid Development: Define your data models in a configuration file, and you get a full CRUD (Create, Read, Update, Delete) API instantly.
  • Rich Features Out-of-the-Box: Eve comes with a ton of advanced features that you'd otherwise have to build yourself:
    • Authentication & Authorization: Support for API keys, HTTP Basic Auth, and Role-Based Access Control (RBAC).
    • Data Validation: Powerful schema-based validation for all incoming data.
    • MongoDB & SQL Support: Primarily designed for MongoDB, but can be extended to work with SQL databases.
    • HATEOAS: Automatically provides links in responses to discover related resources.
    • Caching: Built-in support for Redis and Memcached.
    • Media Resources: Serve files (images, PDFs, etc.) alongside your data.
    • Command-Line Interface (CLI): A handy eve command for running and managing your API server.
  • Clean & Maintainable Code: Your application logic is separated from the API boilerplate, leading to cleaner projects.

Core Concepts

  1. Resource: A resource is a collection of similar items, like users, articles, or products. In Eve, a resource maps directly to a MongoDB collection or an SQL table.
  2. Schema: This is the blueprint for a resource. It defines the fields, their data types (e.g., string, integer, datetime), and validation rules (e.g., minlength, required).
  3. Settings (settings.py): This is the heart of an Eve application. It's a Python file where you define all your resources, their schemas, and global settings for the API (like authentication methods, allowed domains, etc.).
  4. Domain: A domain is a logical grouping of resources. For example, you might have a blog domain containing posts and comments. Eve allows you to serve multiple domains from a single server.

Step-by-Step Example: Building a Simple "Contacts" API

Let's build a simple API to manage a list of contacts.

Step 1: Installation

First, you need to install Eve and its primary dependency, MongoDB.

Python RESTful Eve 如何快速上手?-图2
(图片来源网络,侵删)
# Install Eve
pip install eve

You'll also need a running MongoDB instance. You can easily run one with Docker:

docker run -d -p 27017:27017 --name my-mongo mongo:latest

Step 2: Project Structure

A basic Eve project looks like this:

my_eve_api/
├── settings.py      # Eve's configuration file
└── run.py           # A simple script to run the server

Step 3: Define the Resource in settings.py

This is the most important step. We'll define a people resource with a schema.

# my_eve_api/settings.py
import os
# MongoDB settings
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DBNAME = 'my_api_db'
# Define the resource schema
people_schema = {
    'first_name': {
        'type': 'string',
        'required': True,
        'minlength': 1,
        'maxlength': 50
    },
    'last_name': {
        'type': 'string',
        'required': True,
        'minlength': 1,
        'maxlength': 50
    },
    'email': {
        'type': 'string',
        'required': True,
        'unique': True, # Ensures no two people have the same email
        'regex': '(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)'
    },
    'age': {
        'type': 'integer',
        'min': 0,
        'max': 120
    },
    'contacted': {
        'type': 'boolean',
        'default': False
    }
}
# Define the resource itself
DOMAIN = {
    'people': {
        # The schema for the people resource
        'schema': people_schema,
        # Resource-level settings
        'resource_methods': ['GET', 'POST'], # Allowed methods for the collection
        'item_methods': ['GET', 'PATCH', 'PUT', 'DELETE'], # Allowed methods for a single item
    }
}

Explanation of settings.py:

Python RESTful Eve 如何快速上手?-图3
(图片来源网络,侵删)
  • MONGO_HOST, MONGO_PORT, MONGO_DBNAME: Tell Eve how to connect to your MongoDB instance.
  • people_schema: Defines the structure and validation rules for a "person" document.
  • DOMAIN: A dictionary where each key is a resource name. The value for each key is another dictionary containing settings for that resource.
    • 'schema': Points to our schema definition.
    • 'resource_methods': Defines which HTTP methods are allowed for the entire collection (e.g., GET /people/ and POST /people/).
    • 'item_methods': Defines which HTTP methods are allowed for a single item (e.g., GET /people/one_person_id/).

Step 4: Create the Runner Script (run.py)

This script simply initializes and runs the Eve application.

# my_eve_api/run.py
from eve import Eve
# Eve will automatically look for a file named 'settings.py'
# in the same directory or in the PYTHONPATH.
app = Eve()
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

Step 5: Run the API Server

Navigate to your my_eve_api directory in the terminal and run the script:

python run.py

You should see output indicating that the Eve server is running, usually on http://0.0.0.0:5000.

Step 6: Interact with Your New API

You can now use a tool like curl or Postman to interact with your API.

Create a new person (POST)

curl -i -X POST -H "Content-Type: application/json" -d '{
    "first_name": "John",
    "last_name": "Doe",
    "email": "john.doe@example.com",
    "age": 30
}' http://localhost:5000/people/
  • -i: Shows the response headers, including the Location header with the new resource's URL.
  • -X POST: Specifies the HTTP method.
  • -H: Sets a request header.
  • -d: Sets the request body.

Get all people (GET)

curl http://localhost:5000/people/

This will return a JSON response with your newly created person, including a unique _id generated by MongoDB.

Get a specific person (GET) Copy the _id from the previous response (e.g., 5f8d0d55b54764421b7156c2).

curl http://localhost:5000/people/5f8d0d55b54764421b7156c2/

Update a person (PATCH) Let's update John's age.

curl -i -X PATCH -H "Content-Type: application/json" -d '{
    "age": 31
}' http://localhost:5000/people/5f8d0d55b54764421b7156c2/

Delete a person (DELETE)

curl -i -X DELETE http://localhost:5000/people/5f8d0d55b54764421b7156c2/

Going Further: Authentication

Let's add basic API key authentication to our people resource.

  1. Update settings.py: Add the AUTHENTICATION and RESOURCE_METHODS settings.
# my_eve_api/settings.py
# ... (keep existing MONGO and DOMAIN settings) ...
# Add this new section for authentication
AUTHENTICATION = {
    'DOMAIN': ['people'], # Apply auth to the 'people' resource
    'RESOURCE_METHODS': ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'], # All methods require auth
    'ITEM_METHODS': ['GET', 'PATCH', 'PUT', 'DELETE'],
    'api_key': {
        'source': 'header', # Look for the key in the request header
        'name': 'X-HTTP-API-KEY' # The name of the header
    }
}
# Update the DOMAIN to reflect the new authentication rules
DOMAIN = {
    'people': {
        'schema': people_schema,
        # We now define these in the AUTHENTICATION section, but you can also
        # override them here if needed.
        'resource_methods': ['GET', 'POST'],
        'item_methods': ['GET', 'PATCH', 'PUT', 'DELETE'],
        # Add a unique field for the API key
        'extra_response_fields': ['api_key']
    }
}
# Add a 'users' resource to store our API keys
users_schema = {
    'username': {
        'type': 'string',
        'required': True,
        'unique': True
    },
    'api_key': {
        'type': 'string',
        'required': True,
        'unique': True
    }
}
DOMAIN['users'] = {
    'schema': users_schema,
    'resource_methods': ['POST'], # Allow creating users/keys
    'item_methods': [] # Don't allow updating/deleting keys for simplicity
}
  1. Create an API Key: You can't use the API yet because no key exists. Let's create one by inserting a document directly into the users collection in MongoDB (using a GUI like Compass or the mongo shell).

    // In the mongo shell, switch to your database
    use my_api_db;
    // Insert a new user with an API key
    db.users.insertOne({
        username: "alice",
        api_key: "super-secret-alice-key-12345"
    });
  2. Test with Authentication: Now, try to access the people resource without a key. It will fail with a 401 Unauthorized.

    curl http://localhost:5000/people/
    # -> {"_error": {"code": 401, "message": "Authentication required."}}

    Now, try again with the correct key in the header:

    curl -H "X-HTTP-API-KEY: super-secret-alice-key-12345" http://localhost:5000/people/
    # -> Success! It will return the people data.

Conclusion

Eve is an incredibly powerful tool for building robust RESTful APIs in Python. Its "convention over configuration" approach allows developers to focus on their data model and business logic rather than on the tedious details of request handling, routing, and validation.

While it has a learning curve centered around its configuration system, the time saved in the long run, especially for standard CRUD applications, is immense. If you need a fast, secure, and feature-rich API, Eve is an excellent choice in the Python ecosystem.

分享:
扫描分享到社交APP
上一篇
下一篇