Skip to content

Instantly share code, notes, and snippets.

@halvards
Last active August 3, 2018 03:20
Show Gist options
  • Save halvards/bf189c3919d2e46ffaddc23b0265e373 to your computer and use it in GitHub Desktop.
Save halvards/bf189c3919d2e46ffaddc23b0265e373 to your computer and use it in GitHub Desktop.
Sample request validation WSGI middleware

WSGI middleware can be used to validate incoming requests for APIs implemented in Python.

See middleware.py below for an example that validates the presence of a content key in the JSON body of an incoming HTTP POST request.

appengine_config.py shows how to add this middleware to an application running in Google App Engine Python Standard Environment.

# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.ext import vendor
import middleware
vendor.add('lib')
def webapp_add_wsgi_middleware(app):
return middleware.Validate(app)
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Sample WSGI middleware."""
import logging
import ujson
from webob import Request
from webob.exc import HTTPClientError
class Validate(object):
"""Validate incoming API requests."""
def __init__(self, app):
self._app = app
def __call__(self, environ, start_response):
req = Request(environ)
if (req.method == 'POST' and req.content_type.startswith('application/json')):
request_dict = ujson.loads(req.body)
if 'content' not in request_dict:
logging.info('Rejecting request')
error_resp = HTTPClientError()
error_resp.content_type = 'application/json'
error_resp.content_encoding = 'utf-8'
error_resp.body = ujson.dumps({'error': 'Missing content key in request'}, ensure_ascii=False, indent=2)
return error_resp(environ, start_response)
return self._app(environ, start_response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment