### Launch Eve API Application Source: https://docs.python-eve.org/quickstart This shell command executes the run.py script, starting the Eve API server. It shows the local address where the API is accessible. ```shell $ python run.py * Running on http://127.0.0.1:5000/ ``` -------------------------------- ### Request 'people' Resource from Eve API Source: https://docs.python-eve.org/quickstart This curl command sends a GET request to the '/people' endpoint of the Eve API. This demonstrates accessing a specific resource defined in the application's settings. ```shell $ curl http://127.0.0.1:5000/people ``` -------------------------------- ### Install Eve using pip Source: https://docs.python-eve.org/install This snippet demonstrates the standard way to install the Eve framework using the pip package manager. It fetches the latest stable version of Eve from PyPI and installs it into the current Python environment. ```Shell $ pip install eve ``` -------------------------------- ### Enable CRUD Operations for Eve Resources Source: https://docs.python-eve.org/quickstart This Python configuration line, added to settings.py, enables full CRUD (Create, Read, Update, Delete) operations for resources/collections in Eve. By default, Eve APIs are read-only, so this explicitly allows POST and DELETE methods in addition to GET. ```python # Enable reads (GET), inserts (POST) and DELETE for resources/collections # (if you omit this line, the API will default to ['GET'] and provide # read-only access to the endpoint). RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] # Enable reads (GET), edits (PATCH), replacements (PUT) and deletes of ``` -------------------------------- ### Example JSON Response for Retrieved Person Item Source: https://docs.python-eve.org/quickstart This JSON snippet represents the typical response body when retrieving an individual item from the Eve API. It includes the defined schema fields ('firstname', 'lastname'), along with system-generated fields like '_id', 'updated', 'created', and '_links' for self, parent, and collection navigation, reflecting the configured item title and links. ```JSON { "firstname": "barack", "lastname": "obama", "_id": "50acfba938345b0978fccad7", "updated": "Wed, 21 Nov 2012 16:04:56 GMT", "created": "Wed, 21 Nov 2012 16:04:56 GMT", "_links": { "self": {"href": "people/50acfba938345b0978fccad7", "title": "person"}, "parent": {"href": "/", "title": "home"}, "collection": {"href": "people", "title": "people"} } } ``` -------------------------------- ### Consume Root Eve API Endpoint with Headers Source: https://docs.python-eve.org/quickstart This curl command sends a GET request to the root of the Eve API, including response headers. The output shows the HTTP status, content type, server details, and a JSON payload with available child resources, demonstrating HATEOAS. ```shell $ curl -i http://127.0.0.1:5000 ``` ```http HTTP/1.0 200 OK Content-Type: application/json Content-Length: 82 Server: Eve/0.0.5-dev Werkzeug/0.8.3 Python/2.7.3 Date: Wed, 27 Mar 2013 16:06:44 GMT ``` -------------------------------- ### Example GET Request to Sub-Resource with Query Parameter Source: https://docs.python-eve.org/features This URL demonstrates a GET request to a sub-resource endpoint that includes a 'where' query parameter. This allows clients to further filter the sub-resource collection based on additional criteria, such as an invoice number. ```HTTP people/51f63e0838345b6dcd7eabff/invoices?where={"number": 10} ``` -------------------------------- ### Retrieve Item by Custom 'lastname' Endpoint using cURL Source: https://docs.python-eve.org/quickstart This cURL command demonstrates how to perform a GET request against the custom '/people/' endpoint. It retrieves the item associated with 'obama', showing the HTTP headers (including custom cache control and Etag) and the JSON response body for the retrieved person, confirming the custom endpoint and settings are active. ```Shell $ curl -i http://127.0.0.1:5000/people/obama HTTP/1.0 200 OK Etag: 28995829ee85d69c4c18d597a0f68ae606a266cc Last-Modified: Wed, 21 Nov 2012 16:04:56 GMT Cache-Control: 'max-age=10,must-revalidate' Expires: 10 ... ``` -------------------------------- ### Set up Eve development environment from Git checkout Source: https://docs.python-eve.org/install This snippet outlines the process to set up a development environment for Eve by cloning its Git repository. It creates a virtual environment, activates it, and then installs the local repository in editable mode, allowing for direct development. ```Shell $ git clone https://github.com/pyeve/eve.git Cloning into 'eve'... ... $ cd eve $ virtualenv venv ... Installing setuptools, pip, wheel... done. $ . venv/bin/activate $ pip install . ... Successfully installed ... ``` -------------------------------- ### Install and Activate Pre-commit Hooks Source: https://docs.python-eve.org/contributing Installs the pre-commit framework globally and then activates its hooks for the current repository, ensuring code style and formatting checks run automatically before each commit. ```python pip install --user pre-commit pre-commit install ``` -------------------------------- ### Define Allowed HTTP Methods for Individual Items in Eve Source: https://docs.python-eve.org/quickstart This Python snippet defines the `ITEM_METHODS` global setting, which specifies the HTTP methods (GET, PATCH, PUT, DELETE) allowed for individual item endpoints (e.g., `/people/`) across all resources in an Eve application. This setting can be overridden at the individual endpoint level. ```Python ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] ``` -------------------------------- ### Install Eve development version directly via pip from Git URL Source: https://docs.python-eve.org/install This snippet provides an alternative method to install the development version of Eve without explicitly cloning the repository. It creates a directory, sets up a virtual environment, and then uses pip to install Eve directly from its Git repository URL. ```Shell $ mkdir eve $ cd eve $ virtualenv venv $ . venv/bin/activate $ pip install git+https://github.com/pyeve/eve.git ... Successfully installed ... ``` -------------------------------- ### Create a Minimal Eve Application in Python Source: https://docs.python-eve.org/quickstart This Python script initializes a basic Eve application. It imports the Eve class and runs the application when executed directly. This forms the core of a simple Eve API. ```python from eve import Eve app = Eve() if __name__ == '__main__': app.run() ``` -------------------------------- ### Basic Eve Application Initialization Source: https://docs.python-eve.org/snippets/template This snippet demonstrates the minimal setup for an Eve application. It imports the `Eve` class, initializes an application instance, and runs it, providing a basic web server. ```python from eve import Eve # just an example of a code snippet app = Eve() app.run() ``` -------------------------------- ### Customize 'people' Resource Endpoint Configuration in Eve Source: https://docs.python-eve.org/quickstart This Python snippet shows how to customize the 'people' resource endpoint settings. It includes defining a custom item title, adding an additional read-only lookup endpoint based on 'lastname', overriding global cache control directives, and specifying allowed resource-level HTTP methods (GET, POST), while referencing the previously defined schema. ```Python people = { # 'title' tag used in item links. Defaults to the resource title minus # the final, plural 's' (works fine in most cases but not for 'people') 'item_title': 'person', # by default the standard item entry point is defined as # '/people/'. We leave it untouched, and we also enable an # additional read-only entry point. This way consumers can also perform # GET requests at '/people/'. 'additional_lookup': { 'url': 'regex("[\w]+")', 'field': 'lastname' }, # We choose to override global cache-control directives for this resource. '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 } ``` -------------------------------- ### Define Eve API Resources with settings.py Source: https://docs.python-eve.org/quickstart This Python dictionary defines the accessible resources for the Eve API. Saved as settings.py, it tells Eve that the API exposes a 'people' resource, enabling basic API structure. ```python DOMAIN = {'people': {}} ``` -------------------------------- ### Python Eve Makefile Shortcuts for Development Tasks Source: https://docs.python-eve.org/contributing The Python Eve project provides a `Makefile` with various shortcuts to streamline common development tasks. These commands ensure that all necessary dependencies are installed and provide quick access to actions like running tests, building documentation, performing package checks, and installing development dependencies. ```Shell make test make test-all make docs make check make install-dev ``` -------------------------------- ### Configure MongoDB Connection in Eve settings.py Source: https://docs.python-eve.org/quickstart These Python lines are added to settings.py to configure the MongoDB connection for Eve. It specifies host, port, authentication details, and the database name, enabling Eve to interact with a specific MongoDB instance. ```python # Let's just use the local mongod instance. Edit as needed. # Please note that MONGO_HOST and MONGO_PORT could very well be left # out as they already default to a bare bones local 'mongod' instance. MONGO_HOST = 'localhost' MONGO_PORT = 27017 # Skip this block if your db has no auth. But it really should. MONGO_USERNAME = '' MONGO_PASSWORD = '' # Name of the database on which the user can be authenticated, # needed if --auth mode is enabled. MONGO_AUTH_SOURCE = '' MONGO_DBNAME = 'apitest' ``` -------------------------------- ### Example GET Request to Sub-Resource Endpoint Source: https://docs.python-eve.org/features This snippet shows a typical GET request URL for a sub-resource, targeting invoices associated with a specific contact ID. This endpoint allows clients to retrieve nested data. ```HTTP people/51f63e0838345b6dcd7eabff/invoices ``` -------------------------------- ### Python Eve Document Before PATCH Example Source: https://docs.python-eve.org/features Shows an example of an existing document structure before a PATCH operation. This document contains 'name' and 'contact' fields, with 'contact' having 'email' and 'phone' sub-fields, demonstrating the initial state. ```json { "name": "test account", "contact": { "email": "123@yahoo.com", "phone": "9876543210" } } ``` -------------------------------- ### Install Python Eve in Editable Mode with Development Dependencies Source: https://docs.python-eve.org/contributing Installs the Python Eve project in editable mode, including all development-specific dependencies, which is crucial for local development and testing. ```python pip install -e ".[dev]" ``` -------------------------------- ### Python Eve Example: Hooking into Insert Events Source: https://docs.python-eve.org/features Demonstrates how to register callback functions for `on_insert` and `on_inserted_contacts` events in a Python Eve application. The example shows how to print messages before and after items are stored, illustrating the basic mechanism for extending Eve's functionality. ```Python def before_insert(resource_name, items): print('About to store items to "%s" ' % resource_name) def after_insert_contacts(items): print('About to store contacts') app = Eve() app.on_insert += before_insert app.on_inserted_contacts += after_insert_contacts ``` -------------------------------- ### JSON Payload for 'people' Resource Source: https://docs.python-eve.org/quickstart This JSON object is the response payload for the '/people' resource. It includes an empty '_items' list, '_links' to self and parent resources, and '_meta' data like pagination details. It shows the default structure for an empty collection. ```json { "_items": [], "_links": { "self": { "href": "people", "title": "people" }, "parent": { "href": "/", "title": "home" } }, "_meta": { "max_results": 25, "page": 1, "total": 0 } } ``` -------------------------------- ### Initialize and run a basic Eve REST API with Python Source: https://docs.python-eve.org/index This Python code snippet demonstrates the minimal setup required to bring an Eve REST API online. It imports the `Eve` class, defines a simple domain setting for 'people', initializes the Eve application with these settings, and then runs the application, making the API live. ```Python from eve import Eve settings = {'DOMAIN': {'people': {}}} app = Eve(settings=settings) app.run() ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://docs.python-eve.org/contributing Creates a new Python virtual environment named 'env' and then activates it, isolating project dependencies and ensuring a clean development setup. ```python python3 -m venv env . env/bin/activate # or "env\\Scripts\\activate" on Windows ``` -------------------------------- ### Root Eve API Endpoint JSON Payload Source: https://docs.python-eve.org/quickstart This JSON object represents the payload returned from the root Eve API endpoint. It contains a '_links' object detailing child resources, specifically the 'people' resource, demonstrating HATEOAS principles. ```json { "_links": { "child": [ { "href": "people", "title": "people" } ] } } ``` -------------------------------- ### Configure Eve using a Python dictionary Source: https://docs.python-eve.org/config This Python example illustrates how to configure an Eve application by passing a dictionary of settings directly to the Eve constructor. Unlike file-based configuration, this approach merges the provided settings with Eve's default values, allowing for partial overrides and flexible in-code configuration. ```Python from eve import Eve my_settings = { 'MONGO_HOST': 'localhost', 'MONGO_PORT': 27017, 'MONGO_DBNAME': 'the_db_name', 'DOMAIN': {'contacts': {}} } app = Eve(settings=my_settings) app.run() ``` -------------------------------- ### Pretty Print API Responses Source: https://docs.python-eve.org/features Explains how to format API responses for improved readability by adding the 'pretty' query parameter. The example demonstrates a `curl` request and the resulting indented JSON output. ```curl $ curl -i http://myapi.com/people?pretty\nHTTP/1.1 200 OK\n\n{\n \"_items\": [\n {\n \"_updated\": \"Tue, 19 Apr 2016 08:19:00 GMT\",\n \"firstname\": \"John\",\n \"lastname\": \"Doe\",\n \"born\": \"Thu, 27 Aug 1970 14:37:13 GMT\",\n \"role\": [\n \"author\"\n ],\n \"location\": {\n \"city\": \"Auburn\",\n \"address\": \"422 South Gay Street\"\n },\n \"_links\": {\n \"self\": {\n \"href\": \"people/5715e9f438345b3510d27eb8\",\n \"title\": \"person\"\n }\n },\n \"_created\": \"Tue, 19 Apr 2016 08:19:00 GMT\",\n \"_id\": \"5715e9f438345b3510d27eb8\",\n \"_etag\": \"86dc6b45fe7e2f41f1ca53a0e8fda81224229799\"\n },\n ...\n ]\n} ``` -------------------------------- ### Example: Inserting Data with cURL Source: https://docs.python-eve.org/validation Demonstrates how to send a POST request with JSON data to an Eve API endpoint for inserting new resources. The example shows a request to the /people endpoint with two new entries. ```bash curl -d '[{\"firstname\": \"bill\", \"lastname\": \"clinton\"}, {\"firstname\": \"mitt\", \"lastname\": \"romney\"}]' -H 'Content-Type: application/json' http://myapi/people ``` -------------------------------- ### Update Global Domain Definition with 'people' Resource in Eve Source: https://docs.python-eve.org/quickstart This Python snippet updates the global `DOMAIN` dictionary in Eve settings, integrating the previously defined 'people' resource configuration. This makes the 'people' endpoint available in the API, allowing it to be accessed and managed according to its specific settings. ```Python DOMAIN = { 'people': people, } ``` -------------------------------- ### Run Full Python Eve Test Suite with Tox Source: https://docs.python-eve.org/contributing This command executes the entire test suite across multiple Python versions and dependencies. It requires Python 3.9, 3.10, 3.11, 3.12, and PyPy to be installed. Additionally, an active MongoDB instance running on localhost and a Redis server are necessary for all tests, especially Rate Limiting tests, to execute successfully. ```Shell tox ``` -------------------------------- ### Example HMAC Authorization Header Source: https://docs.python-eve.org/authentication This snippet shows an example of an `Authorization` header used in HMAC authentication. It contains the user ID and the computed HMAC hash, which the server uses to verify the request's authenticity and integrity. ```HTTP Authorization: johndoe:uCMfSzkjue+HSDygYB5aEg== ``` -------------------------------- ### Performing Conditional GET Request with If-None-Match Source: https://docs.python-eve.org/features This cURL command demonstrates how to perform a conditional GET request using the 'If-None-Match' HTTP header with an ETag. If the resource's ETag matches the provided value, the server can respond with a 304 Not Modified, saving bandwidth. ```shell $ curl -H "If-None-Match: 1234567890123456789012345678901234567890" -i http://myapi.com/people/521d6840c437dc0002d1203c ``` -------------------------------- ### Curl Request to Fetch a Resource Collection Source: https://docs.python-eve.org/features Demonstrates a basic curl command to retrieve a collection of resources from an Eve-powered API endpoint. This example shows how to access the default resource endpoint for a 'people' collection. ```shell $ curl -i http://myapi.com/people HTTP/1.1 200 OK ``` -------------------------------- ### Enable JSONP Support in Python Eve Source: https://docs.python-eve.org/features Demonstrates how to enable JSONP in Eve by setting the JSONP_ARGUMENT configuration. It shows a curl command example where a request with the specified argument receives a JSONP-wrapped response. It also notes that CORS is generally preferred over JSONP. ```bash $ curl -i http://localhost:5000/?callback=hello hello() ``` -------------------------------- ### Attempt DELETE on Read-Only Eve API Endpoint Source: https://docs.python-eve.org/quickstart This curl command attempts to send a DELETE request to the '/people' endpoint. Since the API is read-only by default, it receives a '405 Method Not Allowed' HTML response, indicating the operation is not permitted. ```shell $ curl -X DELETE http://127.0.0.1:5000/people ``` ```html 405 Method Not Allowed

Method Not Allowed

The method DELETE is not allowed for the requested URL.

``` -------------------------------- ### Example Sub-Resource Item Endpoint URL Source: https://docs.python-eve.org/features This URL structure represents an endpoint for a specific item within a sub-resource (e.g., a particular invoice for a contact). It implies a two-field lookup on the database, which might have performance implications. ```HTTP people//invoices/ ``` -------------------------------- ### Alternative Querying without Sub-Resources (Contact ID and Number) Source: https://docs.python-eve.org/features This example shows how to query the 'invoices' endpoint directly, filtering by both 'contact_id' and 'number' using a 'where' clause, as an alternative to a sub-resource approach. ```HTTP invoices?where={"contact_id": 51f63e0838345b6dcd7eabff, "number": 10} ``` -------------------------------- ### Consume a Python Eve API using Curl Source: https://docs.python-eve.org/index This command-line snippet shows how to make a GET request to the newly created Eve API endpoint for 'people' using `curl`. It demonstrates how to interact with the live API and expects a 200 OK response, confirming the API is accessible. ```Shell $ curl -i http://example.com/people HTTP/1.1 200 OK ``` -------------------------------- ### Insert Documents into Eve 'people' Endpoint using cURL Source: https://docs.python-eve.org/quickstart This cURL command demonstrates how to insert multiple documents into the '/people' endpoint of an Eve API. It sends a JSON array of two person objects (Barack Obama and Mitt Romney) with a 'Content-Type: application/json' header, resulting in a '201 OK' response upon successful creation. ```Shell $ curl -d '[{\"firstname\": \"barack\", \"lastname\": \"obama\"}, {\"firstname\": \"mitt\", \"lastname\": \"romney\"}]' -H 'Content-Type: application/json' http://127.0.0.1:5000/people HTTP/1.0 201 OK ``` -------------------------------- ### Python Eve Resource Customization Example Source: https://docs.python-eve.org/config This Python dictionary demonstrates how to customize a resource in Python Eve by overriding global API settings. It defines specific behaviors for the 'people' resource, including item title, additional lookup fields, caching directives, and allowed HTTP methods. ```Python people = { # 'title' tag used in item links. Defaults to the resource title minus # the final, plural 's' (works fine in most cases but not for 'people') 'item_title': 'person', # by default, the standard item entry point is defined as # '/people//'. We leave it untouched, and we also enable an # additional read-only entry point. This way consumers can also perform # GET requests at '/people/'. 'additional_lookup': { 'url': 'regex("[\w]+")', 'field': 'lastname' }, # We choose to override global cache-control directives for this resource. 'cache_control': 'max-age=10,must-revalidate', 'cache_expires': 10, # we only allow GET and POST at this resource endpoint. 'resource_methods': ['GET', 'POST'], } ``` -------------------------------- ### Eve Dynamic Database Selection with Basic Authentication Source: https://docs.python-eve.org/authentication This example illustrates how to dynamically select the database for an active request based on the authenticated user. It uses the `set_mongo_prefix()` method within a custom `BasicAuth` class to route users to different MongoDB instances or prefixes based on their credentials. ```Python from eve.auth import BasicAuth class MyBasicAuth(BasicAuth): def check_auth(self, username, password, allowed_roles, resource, method): if username == 'user1': self.set_mongo_prefix('MONGO1') elif username == 'user2': self.set_mongo_prefix('MONGO2') else: # serve all other users from the default db. self.set_mongo_prefix(None) return username is not None and password == 'secret' app = Eve(auth=MyBasicAuth) app.run() ``` -------------------------------- ### Example XML Response from Eve API Source: https://docs.python-eve.org/features This XML snippet shows a typical response from an Eve API when an XML format is requested. It includes 'link' elements with 'rel', 'href', and 'title' attributes, similar to the HATEOAS structure in JSON. ```xml ``` -------------------------------- ### Sort API Resources by Single or Multiple Fields Source: https://docs.python-eve.org/features Provides examples for sorting API results. It covers sorting by multiple fields with ascending/descending order and using native MongoDB-like syntax for sorting parameters. ```curl $ curl -i http://myapi.com/people?sort=city,-lastname\nHTTP/1.1 200 OK ``` ```HTTP http://myapi.com/people?sort=[(\"lastname\", -1)] ``` ```curl $ curl -i http://myapi.com/people?sort=[(%22lastname%22,%20-1)]\nHTTP/1.1 200 OK ``` -------------------------------- ### HTTP Cache Control Headers Example with Curl Source: https://docs.python-eve.org/features Demonstrates an HTTP response including Cache-Control and Expires headers, obtained via a curl command. These headers are crucial for client-side caching, reducing server load by minimizing redundant requests for cached resources. ```bash $ curl -i http://myapi ``` ```http HTTP/1.1 200 OK Content-Type: application/json Content-Length: 131 Cache-Control: max-age=20 Expires: Tue, 22 Jan 2013 09:34:34 GMT Server: Eve/0.0.3 Werkzeug/0.8.3 Python/2.7.3 Date: Tue, 22 Jan 2013 09:34:14 GMT ``` -------------------------------- ### ITEM_METHODS Configuration Source: https://docs.python-eve.org/config Defines the allowed HTTP methods for item-level endpoints. Supports GET, PATCH, PUT, and DELETE. PATCH (or POST with X-HTTP-Method-Override) is used for updates, and DELETE for removal. This setting can be overridden at the resource level. ```APIDOC ITEM_METHODS: A list of HTTP methods supported at item endpoints. Allowed values: GET, PATCH, PUT and DELETE. PATCH or, for clients not supporting PATCH, POST with the X-HTTP-Method-Override header tag, is used for item updates; DELETE for item deletion. Can be overridden by resource settings. Defaults to ['GET']. ``` -------------------------------- ### Define Data Validation Schema for 'people' Resource in Eve Source: https://docs.python-eve.org/quickstart This Python snippet defines a Cerberus-based schema for the 'people' resource. It specifies data types, lengths, required fields, uniqueness constraints (for 'lastname'), and allowed values for fields like 'role'. It also demonstrates embedded dictionaries and datetime types, ensuring proper data validation for incoming requests. ```Python schema = { # Schema definition, based on Cerberus grammar. Check the Cerberus project # (https://github.com/pyeve/cerberus) for details. 'firstname': { 'type': 'string', 'minlength': 1, 'maxlength': 10, }, 'lastname': { 'type': 'string', 'minlength': 1, 'maxlength': 15, 'required': True, # talk about hard constraints! For the purpose of the demo # 'lastname' is an 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', }, } ``` -------------------------------- ### Example JSON Response for Collection Retrieval Source: https://docs.python-eve.org/features Illustrates the typical JSON payload returned by an Eve API when fetching a collection. It includes the `_items` list containing resource data, along with automatically generated metadata fields (`_created`, `_updated`, `_etag`, `_id`), pagination details (`_meta`), and HATEOAS links (`_links`). ```json { "_items": [ { "firstname": "Mark", "lastname": "Green", "born": "Sat, 23 Feb 1985 12:00:00 GMT", "role": ["copy", "author"], "location": {"city": "New York", "address": "4925 Lacross Road"}, "_id": "50bf198338345b1c604faf31", "_updated": "Wed, 05 Dec 2012 09:53:07 GMT", "_created": "Wed, 05 Dec 2012 09:53:07 GMT", "_etag": "ec5e8200b8fa0596afe9ca71a87f23e71ca30e2d", "_links": { "self": {"href": "people/50bf198338345b1c604faf31", "title": "person"} } }, ... ], "_meta": { "max_results": 25, "total": 70, "page": 1 }, "_links": { "self": {"href": "people", "title": "people"}, "parent": {"href": "/", "title": "home"} } } ``` -------------------------------- ### API Rate Limiting: `X-RateLimit` Response Headers Example Source: https://docs.python-eve.org/features This snippet displays the `X-RateLimit-` headers returned in an API response when rate limiting is active in Eve. These headers provide crucial information to the client: `X-RateLimit-Remaining` (requests left), `X-RateLimit-Limit` (total limit), and `X-RateLimit-Reset` (timestamp for reset). ```shell X-RateLimit-Remaining: 299 X-RateLimit-Limit: 300 X-RateLimit-Reset: 1370940300 ``` -------------------------------- ### Example Oplog Entry JSON Structure Source: https://docs.python-eve.org/features This JSON snippet illustrates a typical entry in the Python Eve Operations Log (OpLog). It shows fields like the operation type ('o'), resource ('r'), document ID ('i'), client IP ('ip'), user ('u'), and timestamps. Field names are often shortened for brevity. ```JSON { "o": "DELETE", "r": "people", "i": "542d118938345b614ea75b3c", "c": {...}, "ip": "127.0.0.1", "u": "admin", "_updated": "Fri, 03 Oct 2014 08:16:52 GMT", "_created": "Fri, 03 Oct 2014 08:16:52 GMT", "_etag": "e17218fbca41cb0ee6a5a5933fb9ee4f4ca7e5d6" "_id": "542e5b7438345b6dadf95ba5", "_links": {...} } ``` -------------------------------- ### Logging Inserts to an Internal Resource in Python Eve Source: https://docs.python-eve.org/features Shows how to use Python Eve's data layer to log all inserts to an internal `internal_transactions` endpoint. This example uses an `on_inserted` event hook to capture document IDs and the original resource, then inserts them into the internal resource. ```Python from eve import Eve def on_generic_inserted(self, resource, documents): if resource != 'internal_transactions': dt = datetime.now() transaction = { 'entities': [document['_id'] for document in documents], 'original_resource': resource, config.LAST_UPDATED: dt, config.DATE_CREATED: dt, } app.data.insert('internal_transactions', [transaction]) app = Eve() app.on_inserted += self.on_generic_inserted app.run() ``` -------------------------------- ### Example API Response Payload for Item Endpoint Source: https://docs.python-eve.org/features This JSON object shows a typical response payload for a single item retrieved from an Eve API endpoint. It includes the resource's data fields, metadata like '_id', '_updated', '_created', '_etag', and HATEOAS links for self, parent, and collection navigation. ```JSON { "firstname": "John", "lastname": "Doe", "born": "Thu, 27 Aug 1970 14:37:13 GMT", "role": ["author"], "location": {"city": "Auburn", "address": "422 South Gay Street"}, "_id": "50acfba938345b0978fccad7", "_updated": "Wed, 21 Nov 2012 16:04:56 GMT", "_created": "Wed, 21 Nov 2012 16:04:56 GMT", "_etag": "28995829ee85d69c4c18d597a0f68ae606a266cc", "_links": { "self": {"href": "people/50acfba938345b0978fccad7", "title": "person"}, "parent": {"href": "/", "title": "home"}, "collection": {"href": "people", "title": "people"} } } ``` -------------------------------- ### GET Request Behavior for Soft Deleted Items Source: https://docs.python-eve.org/features Individual GET requests for soft-deleted documents return a `404 Not Found` status, but the response body includes the soft-deleted document with `_deleted: true`. Resource-level GET requests exclude soft-deleted items by default, but they can be included using the `show_deleted` query parameter or explicitly filtered using the `_deleted` field in a `where` clause. ```APIDOC GET /resource/ (for a soft-deleted item): Status: 404 Not Found Body: { "_deleted": true, "_id": "", ...original_data... } GET /resource (default resource-level request): - Excludes documents where _deleted is true GET /resource?show_deleted=true: - Includes all documents (deleted and not deleted) GET /resource?where={"_deleted": true}: - Returns only soft-deleted documents ``` -------------------------------- ### Apply Projections to Filter API Fields with Curl Source: https://docs.python-eve.org/features Illustrates how to use projections to dynamically control which fields are returned by an API endpoint. It provides curl examples for both inclusive (selecting specific fields) and exclusive (excluding specific fields) projections, noting that key fields are always included and some database engines do not allow mixing inclusive and exclusive selections. ```bash $ curl -i -G http://myapi.com/people --data-urlencode 'projection={"lastname": 1, "born": 1}' HTTP/1.1 200 OK ``` ```bash $ curl -i -G http://myapi.com/people --data-urlencode 'projection={"born": 0}' HTTP/1.1 200 OK ``` -------------------------------- ### Build Python Eve Documentation with Sphinx Source: https://docs.python-eve.org/contributing These commands navigate into the 'docs' directory and build the HTML documentation using Sphinx. After execution, the generated documentation can be viewed by opening the 'index.html' file located in the '_build/html' directory in a web browser. ```Shell cd docs make html ``` -------------------------------- ### Database Query for Sub-Resource GET with Filter Source: https://docs.python-eve.org/features This JSON object illustrates the combined database query generated by Eve when a GET request to a sub-resource includes a 'where' parameter. Both the parent resource's ID and the additional filter are applied. ```JSON {'contact_id': '51f63e0838345b6dcd7eabff', "number": 10} ``` -------------------------------- ### Python Eve PATCH Request Body Example Source: https://docs.python-eve.org/features Illustrates a simple PATCH request body targeting the 'email' field within the 'contact' subdocument. This example shows how to update a specific nested field using dot notation. ```json { "contact.email": "xyz@gmail.com" } ``` -------------------------------- ### Initialize Eve with a custom settings file Source: https://docs.python-eve.org/config This Python snippet demonstrates how to instantiate an Eve application by explicitly providing the path to a custom settings file, such as 'my_settings.py'. This method allows the application to load its configuration from a specific Python file, overriding the default settings.py lookup behavior. ```Python from eve import Eve app = Eve(settings='my_settings.py') app.run() ``` -------------------------------- ### Performing Conditional GET Request with If-Modified-Since Source: https://docs.python-eve.org/features This cURL command illustrates how to perform a conditional GET request using the 'If-Modified-Since' HTTP header. If the resource has not been modified since the specified date, the server can respond with a 304 Not Modified, reducing bandwidth. ```shell $ curl -H "If-Modified-Since: Wed, 05 Dec 2012 09:53:07 GMT" -i http://myapi.com/people/521d6840c437dc0002d1203c ``` -------------------------------- ### Database Query for Sub-Resource GET Request Source: https://docs.python-eve.org/features This JSON object represents the underlying database query generated by Eve when a GET request is made to a sub-resource endpoint without additional filters. It automatically includes the parent resource's identifier. ```JSON {'contact_id': '51f63e0838345b6dcd7eabff'} ``` -------------------------------- ### Set Custom Header for Total Count in Python Eve Source: https://docs.python-eve.org/config Specifies a custom HTTP header that will contain the total count of items for collection `GET` requests. This is useful for `HEAD` requests to get item counts without retrieving the full response body. Defaults to `X-Total-Count`. ```APIDOC HEADER_TOTAL_COUNT: str = "X-Total-Count" Description: Custom header for total item count in collection GET responses. ``` -------------------------------- ### Example POST Request Body with Custom UUID ID_FIELD Source: https://docs.python-eve.org/tutorials/custom_idfields Demonstrates how to include a custom UUID value for the `_id` field in a POST request body when `ID_FIELD` auto-generation is not relied upon. The `_id` field is explicitly provided by the client. ```json POST {"name":"bill", "_id":"48c00ee9-4dbe-413f-9fc3-d5f12a91de1c"} ``` -------------------------------- ### Clone Your Forked Eve Repository Source: https://docs.python-eve.org/contributing Clones your personal fork of the Eve repository from GitHub to your local machine and then changes the current directory to the newly cloned repository. ```git git clone https://github.com/{username}/eve cd eve ``` -------------------------------- ### Configure Git Username and Email Globally Source: https://docs.python-eve.org/contributing Sets up global Git configuration for user name and email, which is essential for identifying your commits in the repository. ```git git config --global user.name 'your name' git config --global user.email 'your email' ``` -------------------------------- ### ALLOWED_ITEM_READ_ROLES Configuration Source: https://docs.python-eve.org/config Defines roles allowed to perform GET and OPTIONS methods on item endpoints. This setting can be overridden at the resource level. Consult the Authentication and Authorization section for further information. ```APIDOC ALLOWED_ITEM_READ_ROLES: A list of allowed roles for item endpoints with GET and OPTIONS methods. See Authentication and Authorization for more information. Can be overridden by resource settings. Defaults to []. ``` -------------------------------- ### ALLOWED_READ_ROLES Configuration Source: https://docs.python-eve.org/config Defines roles allowed to perform GET and OPTIONS methods on resource endpoints. This setting can be overridden at the resource level. Consult the Authentication and Authorization section for further information. ```APIDOC ALLOWED_READ_ROLES: A list of allowed roles for resource endpoints with GET and OPTIONS methods. Can be overridden by resource settings. See Authentication and Authorization for more information. Defaults to []. ``` -------------------------------- ### Python Eve: Comprehensive Database Event Hook Overview Source: https://docs.python-eve.org/features Provides a comprehensive overview of all available database event hooks in Python Eve. It details each action (Fetch, Insert, Replace, Update, Delete), when the event fires (Before/After), and the corresponding generic and resource-specific event names with their method signatures. ```APIDOC Action: Fetch Resource: When: After Event name / method signature: - on_fetched_resource(resource_name, response) - on_fetched_resource_(response) Item: When: After Event name / method signature: - on_fetched_item(resource_name, response) - on_fetched_item_(response) Diffs: When: After Event name / method signature: - on_fetched_diffs(resource_name, response) - on_fetched_diffs_(response) Action: Insert Items: When: Before Event name / method signature: - on_insert(resource_name, items) - on_insert_(items) When: After Event name / method signature: - on_inserted(resource_name, items) - on_inserted_(items) Action: Replace Item: When: Before Event name / method signature: - on_replace(resource_name, item, original) - on_replace_(item, original) When: After Event name / method signature: - on_replaced(resource_name, item, original) - on_replaced_(item, original) Action: Update Item: When: Before Event name / method signature: - on_update(resource_name, updates, original) - on_update_(updates, original) When: After Event name / method signature: - on_updated(resource_name, updates, original) - on_updated_(updates, original) Action: Delete Item: When: Before Event name / method signature: - on_delete_item(resource_name, item) - on_delete_item_(item) When: After Event name / method signature: - on_deleted_item(resource_name, item) - on_deleted_item_(item) Resource: When: Before Event name / method signature: - on_delete_resource(resource_name) - on_delete_resource_() - on_delete_resource_originals(resource_name, originals, lookup) - on_delete_resource_originals_(originals, lookup) When: After Event name / method signature: - on_deleted_resource(resource_name) - on_deleted_resource_() ``` -------------------------------- ### CACHE_CONTROL Configuration Source: https://docs.python-eve.org/config Sets the value for the 'Cache-Control' header field for GET requests (e.g., 'max-age=20,must-revalidate'). Leave empty to omit cache directives. This setting can be overridden by resource configurations. ```APIDOC CACHE_CONTROL: Value of the Cache-Control header field used when serving GET requests (e.g., max-age=20,must-revalidate). Leave empty if you don’t want to include cache directives with API responses. Can be overridden by resource settings. Defaults to ''. ``` -------------------------------- ### Set URL Parameter for Showing Soft Deleted Items in Python Eve Source: https://docs.python-eve.org/config Specifies the URL query parameter used to include soft-deleted items in resource-level `GET` responses. Defaults to `show_deleted`. ```APIDOC SHOW_DELETED_PARAM: str = "show_deleted" Description: URL query parameter to include soft-deleted items in GET responses. ``` -------------------------------- ### CACHE_EXPIRES Configuration Source: https://docs.python-eve.org/config Sets the value (in seconds) for the 'Expires' header field for GET requests. If set to a non-zero value, this header will always be included, regardless of the CACHE_CONTROL setting. Can be overridden by resource settings. ```APIDOC CACHE_EXPIRES: Value (in seconds) of the Expires header field used when serving GET requests. If set to a non-zero value, the header will always be included, regardless of the setting of CACHE_CONTROL. Can be overridden by resource settings. Defaults to 0. ``` -------------------------------- ### Configure EXTENDED_MEDIA_INFO for Media Metadata Source: https://docs.python-eve.org/features This Python configuration line demonstrates how to populate the `EXTENDED_MEDIA_INFO` list. This setting allows additional metadata fields like content type, name, and length to be passed through from the underlying media driver. ```Python EXTENDED_MEDIA_INFO = ['content_type', 'name', 'length'] ``` -------------------------------- ### Datasource Keyword Configuration Reference Source: https://docs.python-eve.org/config Provides a comprehensive reference for the `datasource` keyword, outlining its allowed keys and their functionalities for linking API resources to database collections, including data source specification, filtering, projection, sorting, and aggregation settings. ```APIDOC datasource: dict The `datasource` keyword allows to explicitly link API resources to database collections. If omitted, the domain resource key is assumed to also be the name of the database collection. It is a dictionary with four allowed keys: source: string Name of the database collection consumed by the resource. If omitted, the resource name is assumed to also be a valid collection name. filter: dict Database query used to retrieve and validate data. If omitted, by default the whole collection is retrieved. Applied on GET, PATCH and DELETE requests. projection: dict Fieldset exposed by the endpoint. If omitted, by default all fields will be returned to the client. default_sort: list of tuples Default sorting for documents retrieved at the endpoint. Example: `[('name', 1)]`. aggregation: dict Aggregation pipeline and options. When used all other `datasource` settings are ignored, except `source`. The endpoint will be read-only and no item lookup will be available. Defaults to `None`. pipeline: list The aggregation pipeline. Syntax must match the one supported by PyMongo. options: dict Aggregation options. Must be a dictionary with one or more of these keys: allowDiskUse: bool maxTimeMS: int batchSize: int useCursor: bool ``` -------------------------------- ### Run Python Eve Tests with Tox for Linting and Specific Python Versions Source: https://docs.python-eve.org/contributing This command executes the test suite using 'tox', targeting Python 3.10 and 3.9 environments, and also performs coding-style checks (linting). Requires Python 3.9+ to be available on the system. ```Shell $ tox -e linting,py310,py39 ```