This is a small piece of code I’ve found myself usingh quite often when building API’s – what it does, and all it’s meant to do is validate a POST or GET request and return errors and values back to the API function.

I was tired of writing endless “if x in request.POST/GET” lines (particularly for complex requests), so this little function really helped me out to ensure required data was included in the request before even contemplating moving on – and, most importantly, generating a response that could easily be serialised and sent back to the client:

def check_params(request, paramdict, method):
    # Checks for the required aprameters in the request and returns a dict
    # of errors and values
    error = True
    values = {}
    errors = {}
    if method == 'post':
        if request.method == 'POST':
            for p in paramdict:
                if not request.POST.__contains__(p):
                    error = False
                    errors[p] = '; Missing %s paramater' % p
                else:
                    values[p] = request.POST[p]
        else:
            error = False
            errors['method'] = '; request is not POST'
   
    if method == 'get':
        if request.method == 'GET':
            for p in paramdict:
                if not request.GET.__contains__(p):
                    error = False
                    errors[p] = '; Missing %s paramater' % p
                else:
                    values[p] = request.GET[p]
        else:
            error = False
            errors['method'] = '; request is not GET'
   
    return error, errors, values

It’s stupid simple, but became a real crutch for repetitive functions – if anyone has a better way of doing this please let me know!

Happy coding,

Martin

EDIT: Jim (see comments) has suggested a far more elegant solution that would make this a lot shorter and better coded (I freely admit the above is sloppy!):

def checkparam(request, method, params):
    values = None
    errors = []
    if req.method!=method.upper():
        errors[None]='request.method does not match method '+method
   
    else:
        d={'GET':req.GET,
           'POST':req.POST}
        for p in paramdict:
            try:
                values[p]=d[method.upper()][p]
            except:
                errors[p]='parameter '+p+' missing'
               
    return values, errors

Thanks Jim!

EDIT: Another regarding usage – a function such as the above can be thrown into your views to make error checking much faster and easier – for example, consider we have a view at /api/user/get that takes an authtoken, a username and a request_id – I can implement a view something like this:

def get_user(request):
    from django.core import serializers

    values, errors = checkparam(request, ['authtoken',
                                          'username',
                                          'request_id'])
   
    if values:
        try:
            user = User.objects.get(username=values['user'].lower())
        except:
            user = None
       
        data = serializers.serialize("json", user)

        return HttpResponse(data, type='application/json')
   
    else:
        import simplejson
        err_data = simplejson.dumps(errors)
       
        return HttpResponse(err_data, type='application/json')

that’s a basic example – notice how I didn’t need to check the POST or GET objects in what would become a long list of ‘if’ statements, instead, I get back an error dict which I can serialise and send off to the view.