From 08c727add37790b5a556db3fff762f4a27a5c660 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 28 Nov 2014 15:55:02 +0000 Subject: [PATCH] @api_view defaults to allowing GET --- docs/api-guide/views.md | 15 +++++++++++---- rest_framework/decorators.py | 4 +++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 31c62682f..291fe7376 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -127,19 +127,26 @@ REST framework also allows you to work with regular function based views. It pr ## @api_view() -**Signature:** `@api_view(http_method_names)` +**Signature:** `@api_view(http_method_names=['GET'])` -The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: +The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: from rest_framework.decorators import api_view - @api_view(['GET']) + @api_view() def hello_world(request): return Response({"message": "Hello, world!"}) - This view will use the default renderers, parsers, authentication classes etc specified in the [settings]. +By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so: + + @api_view(['GET', 'POST']) + def hello_world(request): + if request.method == 'POST': + return Response({"message": "Got some data!", "data": request.data}) + return Response({"message": "Hello, world!"}) + ## API policy decorators To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes: diff --git a/rest_framework/decorators.py b/rest_framework/decorators.py index d28d6e22a..325435b3f 100644 --- a/rest_framework/decorators.py +++ b/rest_framework/decorators.py @@ -12,12 +12,14 @@ from rest_framework.views import APIView import types -def api_view(http_method_names): +def api_view(http_method_names=None): """ Decorator that converts a function-based view into an APIView subclass. Takes a list of allowed methods for the view as an argument. """ + if http_method_names is None: + http_method_names = ['GET'] def decorator(func):