Skip to content
Snippets Groups Projects
Commit c1f623c1 authored by Prajwal Amin's avatar Prajwal Amin
Browse files

Initial commit

parents
Branches
No related tags found
No related merge requests found
# IDE
.idea
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
LICENSE 0 → 100644
The MIT License (MIT)
Copyright (c) 2015 Akbar Ahmed
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Basic REST API in Python
Example of how to create a basic REST API in Python.
The key components of an API are:
- get inputs
- validate inputs
- logging
- database queries
- check database response (success vs. failure)
- http response
- standardized messaging in response
- error responses
- success responses
- browsable API documentation
- Installation
- Configuration
- Live reload
- Task runner
- Code generation
- Debugging
- Testing
## Dependencies
- Flask: micro-framework for building APIs
- schematics: validation
- psycopg2: PostgreSQL
- cassandra-python: Cassandra
## Steps
- Install Oracle JDK
- Install PyCharm
- Install virtualenv/virtualenvwrapper
```bash
pip install Flask schematics six
```
```bash
mkdir -p ~/repos/basic-python-rest-api && cd $_
```
```bash
vi api.py
```
## Start/stop server
```bash
export API_CONFIG=/path/to/api_config.py
python server.py
```
## Files
`./server.py`
Startup script that calls `api/__init__.py`.
`api/__init__.py`
Create the flask app and import all routes.
`<some package name>/*.py`
All of the Python files that are used to create REST endpoints and the function
that each endpoint is mapped to.
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
app = Flask(__name__)
app.config.from_object('api.config')
#app.config.from_envvar('API_CONFIG')
# ref: https://gist.github.com/ibeex/3257877
formatter = logging.Formatter(
"[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
handler = RotatingFileHandler(app.config['LOG_FILENAME'],
maxBytes=10000000,
backupCount=5)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
app.logger.addHandler(handler)
# Output the access logs to the same file
log = logging.getLogger('werkzeug')
log.setLevel(logging.DEBUG)
log.addHandler(handler)
@app.errorhandler(404)
def page_not_found(e):
return "404 not found", 404
# Import the routes from all controllers
from api.examples import get_example
"""Default configuration settings"""
DEBUG = True
TESTING = False
LOGGER_NAME = 'api-server'
LOG_FILENAME = 'api-server.log'
# API package
The basic structure for each REST resource.
## Function structure
- Get inputs
- Validate inputs
- If validation exception:
- Log exception
- Return error
- Perform logic, file or DB operations
- If error in logic/file/DB operations:
- Log exception
- Return error
- Return response
from api import app
from schematics.models import Model
from schematics.types import IntType, StringType
from schematics.exceptions import ModelConversionError, ModelValidationError
class Example(Model):
"""Validation for Example"""
id = IntType(required=True)
name = StringType(required=True, max_length=5)
@app.route('/examples/<int:example_id>', methods=['GET'])
def get_example(example_id):
"""Get one example's details"""
# Flow
# 1. Get inputs: Parsed by Flask from the URL
# 2. Validate inputs
# 3. If validation exception:
# 3.1 Log exception
# 3.2 Return error
try:
example = Example({
'id': example_id,
'name': '12345787'
})
example.validate()
except ModelConversionError, mce:
# ModelConversionError catches incorrect types
app.logger.exception(mce.messages)
except ModelValidationError, mve:
# ModelValidationError catches validation errors
app.logger.exception(mve.messages)
# debug()
# info()
# warning()
# error()
# exception()
# critical()
# app.logger.debug('Testing the debug log statement')
# app.logger.error('Test error statement')
# app.logger.info('Test info statement')
# Perform logic, file or DB operations
# If error in logic/file/DB operations:
# Log exception
# Return error
# Return response
return "GET one example"
#!/usr/bin/env python
from api import app
app.run()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment