Skip to main content

A collection of tools for APIs

Project description

Cocktail ApiKit

A collection of tools which will be used in all new API project, which including: Bottle, marshmallow, mongo and aws


  • pymongo: 3.7.2
  • marshmallow: 2.16.3
  • bottle: 0.12.16
  • apispec: 0.39.0
  • boto3: 1.9.115
  • botocore: 1.12.115

Usage Example

1. Install cocktail apikit

pip install cocktail-apikit

2. Create a demo project

2.1 Recommend api project structure




2.2 plain text configuration file database.ini

Use $VAR_NAME can support Environment variable, if API_ENV specified, then the corresponding API_ENV configuration will overload the default configurations Be careful all the key defined in the ini file should be declared in the project level Settings class

; Support Environment variable 

;DB_NAME = develop_db
DEMO_COLLECTION = demo_collection

;DB_NAME = test_db
DEMO_COLLECTION = demo_collection

2.3 content of project level setting file

import os
from cocktail_apikit import DefaultSettings
class Settings(DefaultSettings):

    # specify configuration file names to load configuration from file
    # Be aware, any configuration fields in configuration file should be 
    # declare in the settings class  or any its super class, just 
    # to make us have better IDE auto-complete help
    _config_files = ['config/database.ini']

    # **REQUIRED: for Settings class can find the files in the _config_files attribute in any situation**
    BASE_DIR = os.path.dirname(os.path.abspath(__file__)) 

2.4 content of a demo Schema in schema/

from marshmallow import fields 
from cocktail_apikit import BaseSchema 

class DemoSchema(BaseSchema):
    BaseSchema included some common fields: id, created_at, updated_at, deleted_at;
    Also contains some util method from SchemaMongoMixin for communicate with mongo db
    name = fields.Str()

2.5 content of a endpoint Resource in api/

from settings import Settings
from bottle import request 
from schema.demo import DemoSchema

from cocktail_apikit import (
    ResourcePlugin,  route_mark,  ValidationError,  MongoDBManager,  enable_cors,
    BottleMongoQueryBuilder, Pagination, HTTP_DELETE_OK, HTTP_UPDATE_OK

demo_db = MongoDBManager(Settings.mongo_config_for_collection('demo')) # specify a Config option name or be the given name
demo_schema = DemoSchema()

class DemoResource(ResourcePlugin):

    # a simple demo endpoint
    def index(self):
        return 'hello cocktail apikit'

    @enable_cors # allow cors for endpoint
    def list_demo(self):

        mongo_query_builder = BottleMongoQueryBuilder(request, demo_schema)
        mongo_query = mongo_query_builder.to_mongo_query()
        results, count = demo_db.filter(mongo_query)
        pagination = Pagination(mongo_query, results, count)
        return pagination.serialize(demo_schema)

    @route_mark('/demos', 'POST')
    def create_demo(self):
        payload = request.json
        cleaned_obj, errors = demo_schema.load(payload)
        if errors:
            raise ValidationError(errors)

        created_ids, errors = demo_db.create(cleaned_obj)

        if errors:
            raise ValidationError(errors)

        return {
            "ids": created_ids 

    @route_mark('/demos/<demo_id>', 'DELETE')
    def soft_delete_demo(self, demo_id):
        delete_condition = {'_id':demo_id}

        result, errors = demo_db.delete(delete_condition)

        if errors:
            raise ValidationError(errors)

        if not result.raw_result['updatedExiting']:
            raise ValidationError({
                'msg': 'Object does not exist or already deleted!'
        return {

    @route_mark('/demos/<demo_id>', ['PUT','PATCH'])
    def update_demo(self, demo_id):
        payload = request.json
        condition = {'_id':demo_id}

        result, errors = demo_db.update(condition, payload)
        if errors:
            raise ValidationError(errors)
        if not result.raw_result['updatedExisting']:
            raise ValidationError({
                'msg': 'Does not found any thing to udpate'
        return {'msg':HTTP_UPDATE_OK}

2.6 content of main

from bottle import Bottle
from cocktail_apikit import FlexibleJsonPlugin, CorsPlugin, APP_ERROR_HANDLER
from api.demo import DemoResource

app  = Bottle()

# install FlexibleJsonPlugin to enable handle more data type

# install endpoint resource class`s instance


#config application object's error handlers
app.error_handler = APP_ERROR_HANDLER

if __name__ == "__main__":, debug=True, reloader=True)

2.7 Then we can run 'python', and access

### Create a demo
POST http://localhost:8000/demos

  "name": "test1"

### list all demos
GET  http://localhost:8000/demos

### update a demo
PUT http://localhost:8000/demos/<demo_id>

### delete a demo
DELETE http://localhost:8000/demos/<demo_id>

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for cocktail-apikit, version 0.0.10
Filename, size File type Python version Upload date Hashes
Filename, size cocktail_apikit-0.0.10-py3-none-any.whl (20.0 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size cocktail-apikit-0.0.10.tar.gz (17.1 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page