diff --git a/404.html b/404.html index 565966c1f..d6669d7e5 100644 --- a/404.html +++ b/404.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/authentication/index.html b/api-guide/authentication/index.html index 3b4cb41f9..5d962979f 100644 --- a/api-guide/authentication/index.html +++ b/api-guide/authentication/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/content-negotiation/index.html b/api-guide/content-negotiation/index.html index ef717d99b..3a4945134 100644 --- a/api-guide/content-negotiation/index.html +++ b/api-guide/content-negotiation/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/exceptions/index.html b/api-guide/exceptions/index.html index ac1c968d9..42c394b79 100644 --- a/api-guide/exceptions/index.html +++ b/api-guide/exceptions/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/fields/index.html b/api-guide/fields/index.html index 645417d36..c6a936865 100644 --- a/api-guide/fields/index.html +++ b/api-guide/fields/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - @@ -633,6 +637,7 @@ Set to false if this field is not required to be present during deserialization.

    If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.

    The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.

    May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a set_context method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for validators.

    +

    When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance.

    Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.

    source

    The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email').

    diff --git a/api-guide/filtering/index.html b/api-guide/filtering/index.html index 6f3c07e87..b2a9207d5 100644 --- a/api-guide/filtering/index.html +++ b/api-guide/filtering/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/format-suffixes/index.html b/api-guide/format-suffixes/index.html index d2b8479f5..588242389 100644 --- a/api-guide/format-suffixes/index.html +++ b/api-guide/format-suffixes/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/generic-views/index.html b/api-guide/generic-views/index.html index ed5a0ec15..95256b392 100644 --- a/api-guide/generic-views/index.html +++ b/api-guide/generic-views/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - @@ -571,7 +575,7 @@ class UserList(generics.ListCreateAPIView):

    Pagination:

    The following attributes are used to control pagination when used with list views.

    Filtering:

    diff --git a/api-guide/pagination/index.html b/api-guide/pagination/index.html index 2f8e22592..a1b94a7f1 100644 --- a/api-guide/pagination/index.html +++ b/api-guide/pagination/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/parsers/index.html b/api-guide/parsers/index.html index 544263321..941e2e5de 100644 --- a/api-guide/parsers/index.html +++ b/api-guide/parsers/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/permissions/index.html b/api-guide/permissions/index.html index 8ff3e3cda..30649c618 100644 --- a/api-guide/permissions/index.html +++ b/api-guide/permissions/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/relations/index.html b/api-guide/relations/index.html index 20d0022b6..73b90f7f9 100644 --- a/api-guide/relations/index.html +++ b/api-guide/relations/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/renderers/index.html b/api-guide/renderers/index.html index 5330d80b4..f61869585 100644 --- a/api-guide/renderers/index.html +++ b/api-guide/renderers/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/requests/index.html b/api-guide/requests/index.html index 41e4f6d80..5577c71c1 100644 --- a/api-guide/requests/index.html +++ b/api-guide/requests/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/responses/index.html b/api-guide/responses/index.html index f533553b0..f492f41d8 100644 --- a/api-guide/responses/index.html +++ b/api-guide/responses/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/reverse/index.html b/api-guide/reverse/index.html index 2b1f7484e..c242e9540 100644 --- a/api-guide/reverse/index.html +++ b/api-guide/reverse/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/routers/index.html b/api-guide/routers/index.html index 8d976ff77..51c809381 100644 --- a/api-guide/routers/index.html +++ b/api-guide/routers/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/schemas/index.html b/api-guide/schemas/index.html index 8351748c3..2942068af 100644 --- a/api-guide/schemas/index.html +++ b/api-guide/schemas/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/serializers/index.html b/api-guide/serializers/index.html index 8c790b309..3c12159e5 100644 --- a/api-guide/serializers/index.html +++ b/api-guide/serializers/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/settings/index.html b/api-guide/settings/index.html index ae6828fe9..bf899fcee 100644 --- a/api-guide/settings/index.html +++ b/api-guide/settings/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/status-codes/index.html b/api-guide/status-codes/index.html index b555845ca..07882aea7 100644 --- a/api-guide/status-codes/index.html +++ b/api-guide/status-codes/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/testing/index.html b/api-guide/testing/index.html index d586e71d8..a240a3ab7 100644 --- a/api-guide/testing/index.html +++ b/api-guide/testing/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/throttling/index.html b/api-guide/throttling/index.html index d38baf817..be1bc8154 100644 --- a/api-guide/throttling/index.html +++ b/api-guide/throttling/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/validators/index.html b/api-guide/validators/index.html index b29d1e01b..f49a5f04f 100644 --- a/api-guide/validators/index.html +++ b/api-guide/validators/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/versioning/index.html b/api-guide/versioning/index.html index 0de883432..9d0930c28 100644 --- a/api-guide/versioning/index.html +++ b/api-guide/versioning/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/views/index.html b/api-guide/views/index.html index cd6c36dd8..0fd6de70c 100644 --- a/api-guide/views/index.html +++ b/api-guide/views/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/api-guide/viewsets/index.html b/api-guide/viewsets/index.html index 60309d6a9..ab961839e 100644 --- a/api-guide/viewsets/index.html +++ b/api-guide/viewsets/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/img/api-docs.gif b/img/api-docs.gif new file mode 100644 index 000000000..6da560b7e Binary files /dev/null and b/img/api-docs.gif differ diff --git a/img/api-docs.png b/img/api-docs.png new file mode 100644 index 000000000..939075a89 Binary files /dev/null and b/img/api-docs.png differ diff --git a/index.html b/index.html index 36bfc148d..dd10831c9 100644 --- a/index.html +++ b/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - @@ -550,7 +554,7 @@ continued development by signing up for a paid @@ -704,7 +708,7 @@ Framework.

    If you believe you’ve found something in Django REST framework which has security implications, please do not raise the issue in a public forum.

    Send a description of the issue via email to rest-framework-security@googlegroups.com. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.

    License

    -

    Copyright (c) 2011-2016, Tom Christie +

    Copyright (c) 2011-2017, Tom Christie All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    diff --git a/mkdocs/search_index.json b/mkdocs/search_index.json index ca98c2bd3..b4ea87de4 100644 --- a/mkdocs/search_index.json +++ b/mkdocs/search_index.json @@ -2,7 +2,7 @@ "docs": [ { "location": "/", - "text": ".promo li a {\n float: left;\n width: 130px;\n height: 20px;\n text-align: center;\n margin: 10px 30px;\n padding: 150px 0 0 0;\n background-position: 0 50%;\n background-size: 130px auto;\n background-repeat: no-repeat;\n font-size: 120%;\n color: black;\n}\n.promo li {\n list-style: none;\n}\n\n\n\n\n\n \n\n\n \n\n \n\n \n\n\n \n\n \n\n \n\n\n\n\n\n\n\nNote\n: This is the documentation for the \nversion 3\n of REST framework. Documentation for \nversion 2\n is also available.\n\n\n\n\n\n\nDjango REST Framework\n\n\n\n\n\n\n\n\nDjango REST framework is a powerful and flexible toolkit for building Web APIs.\n\n\nSome reasons you might want to use REST framework:\n\n\n\n\nThe \nWeb browsable API\n is a huge usability win for your developers.\n\n\nAuthentication policies\n including packages for \nOAuth1a\n and \nOAuth2\n.\n\n\nSerialization\n that supports both \nORM\n and \nnon-ORM\n data sources.\n\n\nCustomizable all the way down - just use \nregular function-based views\n if you don't need the \nmore\n \npowerful\n \nfeatures\n.\n\n\nExtensive documentation\n, and \ngreat community support\n.\n\n\nUsed and trusted by internationally recognised companies including \nMozilla\n, \nRed Hat\n, \nHeroku\n, and \nEventbrite\n.\n\n\n\n\n\n\nFunding\n\n\nREST framework is a \ncollaboratively funded project\n. If you use\nREST framework commercially we strongly encourage you to invest in its\ncontinued development by \nsigning up for a paid plan\n.\n\n\nThe initial aim is to provide a single full-time position on REST framework.\n\nEvery single sign-up makes a significant impact towards making that possible.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n \nRollbar\n\n \nMicroPyramid\n\n\n\n\n\n\n\n\nMany thanks to all our \nwonderful sponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, \nRollbar\n, and \nMicroPyramid\n.\n\n\n\n\nRequirements\n\n\nREST framework requires the following:\n\n\n\n\nPython (2.7, 3.2, 3.3, 3.4, 3.5)\n\n\nDjango (1.8, 1.9, 1.10)\n\n\n\n\nThe following packages are optional:\n\n\n\n\ncoreapi\n (1.32.0+) - Schema generation support.\n\n\nMarkdown\n (2.1.0+) - Markdown support for the browsable API.\n\n\ndjango-filter\n (0.9.2+) - Filtering support.\n\n\ndjango-crispy-forms\n - Improved HTML display for filtering.\n\n\ndjango-guardian\n (1.1.1+) - Object level permissions support.\n\n\n\n\nInstallation\n\n\nInstall using \npip\n, including any optional packages you want...\n\n\npip install djangorestframework\npip install markdown # Markdown support for the browsable API.\npip install django-filter # Filtering support\n\n\n\n...or clone the project from github.\n\n\ngit clone git@github.com:tomchristie/django-rest-framework.git\n\n\n\nAdd \n'rest_framework'\n to your \nINSTALLED_APPS\n setting.\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\n\n\nIf you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root \nurls.py\n file.\n\n\nurlpatterns = [\n ...\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nNote that the URL path can be whatever you want, but you must include \n'rest_framework.urls'\n with the \n'rest_framework'\n namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.\n\n\nExample\n\n\nLet's take a look at a quick example of using REST framework to build a simple model-backed API.\n\n\nWe'll create a read-write API for accessing information on the users of our project.\n\n\nAny global settings for a REST framework API are kept in a single configuration dictionary named \nREST_FRAMEWORK\n. Start off by adding the following to your \nsettings.py\n module:\n\n\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ]\n}\n\n\n\nDon't forget to make sure you've also added \nrest_framework\n to your \nINSTALLED_APPS\n.\n\n\nWe're ready to create our API now.\nHere's our project's root \nurls.py\n module:\n\n\nfrom django.conf.urls import url, include\nfrom django.contrib.auth.models import User\nfrom rest_framework import routers, serializers, viewsets\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'is_staff')\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nYou can now open the API in your browser at \nhttp://127.0.0.1:8000/\n, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.\n\n\nQuickstart\n\n\nCan't wait to get started? The \nquickstart guide\n is the fastest way to get up and running, and building APIs with REST framework.\n\n\nTutorial\n\n\nThe tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.\n\n\n\n\n1 - Serialization\n\n\n2 - Requests \n Responses\n\n\n3 - Class-based views\n\n\n4 - Authentication \n permissions\n\n\n5 - Relationships \n hyperlinked APIs\n\n\n6 - Viewsets \n routers\n\n\n7 - Schemas \n client libraries\n\n\n\n\nThere is a live example API of the finished tutorial API for testing purposes, \navailable here\n.\n\n\nAPI Guide\n\n\nThe API guide is your complete reference manual to all the functionality provided by REST framework.\n\n\n\n\nRequests\n\n\nResponses\n\n\nViews\n\n\nGeneric views\n\n\nViewsets\n\n\nRouters\n\n\nParsers\n\n\nRenderers\n\n\nSerializers\n\n\nSerializer fields\n\n\nSerializer relations\n\n\nValidators\n\n\nAuthentication\n\n\nPermissions\n\n\nThrottling\n\n\nFiltering\n\n\nPagination\n\n\nVersioning\n\n\nContent negotiation\n\n\nMetadata\n\n\nSchemas\n\n\nFormat suffixes\n\n\nReturning URLs\n\n\nExceptions\n\n\nStatus codes\n\n\nTesting\n\n\nSettings\n\n\n\n\nTopics\n\n\nGeneral guides to using REST framework.\n\n\n\n\nDocumenting your API\n\n\nAPI Clients\n\n\nInternationalization\n\n\nAJAX, CSRF \n CORS\n\n\nHTML \n Forms\n\n\nBrowser enhancements\n\n\nThe Browsable API\n\n\nREST, Hypermedia \n HATEOAS\n\n\nThird Party Packages\n\n\nTutorials and Resources\n\n\nContributing to REST framework\n\n\nProject management\n\n\n3.0 Announcement\n\n\n3.1 Announcement\n\n\n3.2 Announcement\n\n\n3.3 Announcement\n\n\n3.4 Announcement\n\n\n3.5 Announcement\n\n\nKickstarter Announcement\n\n\nMozilla Grant\n\n\nFunding\n\n\nRelease Notes\n\n\nJobs\n\n\n\n\nDevelopment\n\n\nSee the \nContribution guidelines\n for information on how to clone\nthe repository, run the test suite and contribute changes back to REST\nFramework.\n\n\nSupport\n\n\nFor support please see the \nREST framework discussion group\n, try the \n#restframework\n channel on \nirc.freenode.net\n, search \nthe IRC archives\n, or raise a question on \nStack Overflow\n, making sure to include the \n'django-rest-framework'\n tag.\n\n\nFor priority support please sign up for a \nprofessional or premium sponsorship plan\n.\n\n\nFor updates on REST framework development, you may also want to follow \nthe author\n on Twitter.\n\n\nFollow @_tomchristie\n\n\n!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");\n\n\nSecurity\n\n\nIf you believe you\u2019ve found something in Django REST framework which has security implications, please \ndo not raise the issue in a public forum\n.\n\n\nSend a description of the issue via email to \nrest-framework-security@googlegroups.com\n. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.\n\n\nLicense\n\n\nCopyright (c) 2011-2016, Tom Christie\nAll rights reserved.\n\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", + "text": ".promo li a {\n float: left;\n width: 130px;\n height: 20px;\n text-align: center;\n margin: 10px 30px;\n padding: 150px 0 0 0;\n background-position: 0 50%;\n background-size: 130px auto;\n background-repeat: no-repeat;\n font-size: 120%;\n color: black;\n}\n.promo li {\n list-style: none;\n}\n\n\n\n\n\n \n\n\n \n\n \n\n \n\n\n \n\n \n\n \n\n\n\n\n\n\n\nNote\n: This is the documentation for the \nversion 3\n of REST framework. Documentation for \nversion 2\n is also available.\n\n\n\n\n\n\nDjango REST Framework\n\n\n\n\n\n\n\n\nDjango REST framework is a powerful and flexible toolkit for building Web APIs.\n\n\nSome reasons you might want to use REST framework:\n\n\n\n\nThe \nWeb browsable API\n is a huge usability win for your developers.\n\n\nAuthentication policies\n including packages for \nOAuth1a\n and \nOAuth2\n.\n\n\nSerialization\n that supports both \nORM\n and \nnon-ORM\n data sources.\n\n\nCustomizable all the way down - just use \nregular function-based views\n if you don't need the \nmore\n \npowerful\n \nfeatures\n.\n\n\nExtensive documentation\n, and \ngreat community support\n.\n\n\nUsed and trusted by internationally recognised companies including \nMozilla\n, \nRed Hat\n, \nHeroku\n, and \nEventbrite\n.\n\n\n\n\n\n\nFunding\n\n\nREST framework is a \ncollaboratively funded project\n. If you use\nREST framework commercially we strongly encourage you to invest in its\ncontinued development by \nsigning up for a paid plan\n.\n\n\nThe initial aim is to provide a single full-time position on REST framework.\n\nEvery single sign-up makes a significant impact towards making that possible.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n \nRollbar\n\n \nMicroPyramid\n\n\n\n\n\n\n\n\nMany thanks to all our \nwonderful sponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, \nRollbar\n, and \nMicroPyramid\n.\n\n\n\n\nRequirements\n\n\nREST framework requires the following:\n\n\n\n\nPython (2.7, 3.2, 3.3, 3.4, 3.5)\n\n\nDjango (1.8, 1.9, 1.10)\n\n\n\n\nThe following packages are optional:\n\n\n\n\ncoreapi\n (1.32.0+) - Schema generation support.\n\n\nMarkdown\n (2.1.0+) - Markdown support for the browsable API.\n\n\ndjango-filter\n (1.0.1+) - Filtering support.\n\n\ndjango-crispy-forms\n - Improved HTML display for filtering.\n\n\ndjango-guardian\n (1.1.1+) - Object level permissions support.\n\n\n\n\nInstallation\n\n\nInstall using \npip\n, including any optional packages you want...\n\n\npip install djangorestframework\npip install markdown # Markdown support for the browsable API.\npip install django-filter # Filtering support\n\n\n\n...or clone the project from github.\n\n\ngit clone git@github.com:tomchristie/django-rest-framework.git\n\n\n\nAdd \n'rest_framework'\n to your \nINSTALLED_APPS\n setting.\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n)\n\n\n\nIf you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root \nurls.py\n file.\n\n\nurlpatterns = [\n ...\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nNote that the URL path can be whatever you want, but you must include \n'rest_framework.urls'\n with the \n'rest_framework'\n namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.\n\n\nExample\n\n\nLet's take a look at a quick example of using REST framework to build a simple model-backed API.\n\n\nWe'll create a read-write API for accessing information on the users of our project.\n\n\nAny global settings for a REST framework API are kept in a single configuration dictionary named \nREST_FRAMEWORK\n. Start off by adding the following to your \nsettings.py\n module:\n\n\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ]\n}\n\n\n\nDon't forget to make sure you've also added \nrest_framework\n to your \nINSTALLED_APPS\n.\n\n\nWe're ready to create our API now.\nHere's our project's root \nurls.py\n module:\n\n\nfrom django.conf.urls import url, include\nfrom django.contrib.auth.models import User\nfrom rest_framework import routers, serializers, viewsets\n\n# Serializers define the API representation.\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'username', 'email', 'is_staff')\n\n# ViewSets define the view behavior.\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n# Routers provide an easy way of automatically determining the URL conf.\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n\n\n\nYou can now open the API in your browser at \nhttp://127.0.0.1:8000/\n, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.\n\n\nQuickstart\n\n\nCan't wait to get started? The \nquickstart guide\n is the fastest way to get up and running, and building APIs with REST framework.\n\n\nTutorial\n\n\nThe tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.\n\n\n\n\n1 - Serialization\n\n\n2 - Requests \n Responses\n\n\n3 - Class-based views\n\n\n4 - Authentication \n permissions\n\n\n5 - Relationships \n hyperlinked APIs\n\n\n6 - Viewsets \n routers\n\n\n7 - Schemas \n client libraries\n\n\n\n\nThere is a live example API of the finished tutorial API for testing purposes, \navailable here\n.\n\n\nAPI Guide\n\n\nThe API guide is your complete reference manual to all the functionality provided by REST framework.\n\n\n\n\nRequests\n\n\nResponses\n\n\nViews\n\n\nGeneric views\n\n\nViewsets\n\n\nRouters\n\n\nParsers\n\n\nRenderers\n\n\nSerializers\n\n\nSerializer fields\n\n\nSerializer relations\n\n\nValidators\n\n\nAuthentication\n\n\nPermissions\n\n\nThrottling\n\n\nFiltering\n\n\nPagination\n\n\nVersioning\n\n\nContent negotiation\n\n\nMetadata\n\n\nSchemas\n\n\nFormat suffixes\n\n\nReturning URLs\n\n\nExceptions\n\n\nStatus codes\n\n\nTesting\n\n\nSettings\n\n\n\n\nTopics\n\n\nGeneral guides to using REST framework.\n\n\n\n\nDocumenting your API\n\n\nAPI Clients\n\n\nInternationalization\n\n\nAJAX, CSRF \n CORS\n\n\nHTML \n Forms\n\n\nBrowser enhancements\n\n\nThe Browsable API\n\n\nREST, Hypermedia \n HATEOAS\n\n\nThird Party Packages\n\n\nTutorials and Resources\n\n\nContributing to REST framework\n\n\nProject management\n\n\n3.0 Announcement\n\n\n3.1 Announcement\n\n\n3.2 Announcement\n\n\n3.3 Announcement\n\n\n3.4 Announcement\n\n\n3.5 Announcement\n\n\nKickstarter Announcement\n\n\nMozilla Grant\n\n\nFunding\n\n\nRelease Notes\n\n\nJobs\n\n\n\n\nDevelopment\n\n\nSee the \nContribution guidelines\n for information on how to clone\nthe repository, run the test suite and contribute changes back to REST\nFramework.\n\n\nSupport\n\n\nFor support please see the \nREST framework discussion group\n, try the \n#restframework\n channel on \nirc.freenode.net\n, search \nthe IRC archives\n, or raise a question on \nStack Overflow\n, making sure to include the \n'django-rest-framework'\n tag.\n\n\nFor priority support please sign up for a \nprofessional or premium sponsorship plan\n.\n\n\nFor updates on REST framework development, you may also want to follow \nthe author\n on Twitter.\n\n\nFollow @_tomchristie\n\n\n!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=\"//platform.twitter.com/widgets.js\";fjs.parentNode.insertBefore(js,fjs);}}(document,\"script\",\"twitter-wjs\");\n\n\nSecurity\n\n\nIf you believe you\u2019ve found something in Django REST framework which has security implications, please \ndo not raise the issue in a public forum\n.\n\n\nSend a description of the issue via email to \nrest-framework-security@googlegroups.com\n. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.\n\n\nLicense\n\n\nCopyright (c) 2011-2017, Tom Christie\nAll rights reserved.\n\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n\nRedistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "title": "Home" }, { @@ -12,7 +12,7 @@ }, { "location": "/#requirements", - "text": "REST framework requires the following: Python (2.7, 3.2, 3.3, 3.4, 3.5) Django (1.8, 1.9, 1.10) The following packages are optional: coreapi (1.32.0+) - Schema generation support. Markdown (2.1.0+) - Markdown support for the browsable API. django-filter (0.9.2+) - Filtering support. django-crispy-forms - Improved HTML display for filtering. django-guardian (1.1.1+) - Object level permissions support.", + "text": "REST framework requires the following: Python (2.7, 3.2, 3.3, 3.4, 3.5) Django (1.8, 1.9, 1.10) The following packages are optional: coreapi (1.32.0+) - Schema generation support. Markdown (2.1.0+) - Markdown support for the browsable API. django-filter (1.0.1+) - Filtering support. django-crispy-forms - Improved HTML display for filtering. django-guardian (1.1.1+) - Object level permissions support.", "title": "Requirements" }, { @@ -62,7 +62,7 @@ }, { "location": "/#license", - "text": "Copyright (c) 2011-2016, Tom Christie\nAll rights reserved. Redistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", + "text": "Copyright (c) 2011-2017, Tom Christie\nAll rights reserved. Redistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "title": "License" }, { @@ -107,7 +107,7 @@ }, { "location": "/tutorial/1-serialization/", - "text": "Tutorial 1: Serialization\n\n\nIntroduction\n\n\nThis tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.\n\n\nThe tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the \nquickstart\n documentation instead.\n\n\n\n\nNote\n: The code for this tutorial is available in the \ntomchristie/rest-framework-tutorial\n repository on GitHub. The completed implementation is also online as a sandbox version for testing, \navailable here\n.\n\n\n\n\nSetting up a new environment\n\n\nBefore we do anything else we'll create a new virtual environment, using \nvirtualenv\n. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.\n\n\nvirtualenv env\nsource env/bin/activate\n\n\n\nNow that we're inside a virtualenv environment, we can install our package requirements.\n\n\npip install django\npip install djangorestframework\npip install pygments # We'll be using this for the code highlighting\n\n\n\nNote:\n To exit the virtualenv environment at any time, just type \ndeactivate\n. For more information see the \nvirtualenv documentation\n.\n\n\nGetting started\n\n\nOkay, we're ready to get coding.\nTo get started, let's create a new project to work with.\n\n\ncd ~\ndjango-admin.py startproject tutorial\ncd tutorial\n\n\n\nOnce that's done we can create an app that we'll use to create a simple Web API.\n\n\npython manage.py startapp snippets\n\n\n\nWe'll need to add our new \nsnippets\n app and the \nrest_framework\n app to \nINSTALLED_APPS\n. Let's edit the \ntutorial/settings.py\n file:\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n 'snippets.apps.SnippetsConfig',\n)\n\n\n\nPlease note that if you're using Django \n1.9, you need to replace \nsnippets.apps.SnippetsConfig\n with \nsnippets\n.\n\n\nOkay, we're ready to roll.\n\n\nCreating a model to work with\n\n\nFor the purposes of this tutorial we're going to start by creating a simple \nSnippet\n model that is used to store code snippets. Go ahead and edit the \nsnippets/models.py\n file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.\n\n\nfrom django.db import models\nfrom pygments.lexers import get_all_lexers\nfrom pygments.styles import get_all_styles\n\nLEXERS = [item for item in get_all_lexers() if item[1]]\nLANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])\nSTYLE_CHOICES = sorted((item, item) for item in get_all_styles())\n\n\nclass Snippet(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n title = models.CharField(max_length=100, blank=True, default='')\n code = models.TextField()\n linenos = models.BooleanField(default=False)\n language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)\n style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)\n\n class Meta:\n ordering = ('created',)\n\n\n\nWe'll also need to create an initial migration for our snippet model, and sync the database for the first time.\n\n\npython manage.py makemigrations snippets\npython manage.py migrate\n\n\n\nCreating a Serializer class\n\n\nThe first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as \njson\n. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the \nsnippets\n directory named \nserializers.py\n and add the following.\n\n\nfrom rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n code = serializers.CharField(style={'base_template': 'textarea.html'})\n linenos = serializers.BooleanField(required=False)\n language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')\n style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Snippet` instance, given the validated data.\n \"\"\"\n return Snippet.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Snippet` instance, given the validated data.\n \"\"\"\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\n\n\nThe first part of the serializer class defines the fields that get serialized/deserialized. The \ncreate()\n and \nupdate()\n methods define how fully fledged instances are created or modified when calling \nserializer.save()\n\n\nA serializer class is very similar to a Django \nForm\n class, and includes similar validation flags on the various fields, such as \nrequired\n, \nmax_length\n and \ndefault\n.\n\n\nThe field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The \n{'base_template': 'textarea.html'}\n flag above is equivalent to using \nwidget=widgets.Textarea\n on a Django \nForm\n class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.\n\n\nWe can actually also save ourselves some time by using the \nModelSerializer\n class, as we'll see later, but for now we'll keep our serializer definition explicit.\n\n\nWorking with Serializers\n\n\nBefore we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.\n\n\npython manage.py shell\n\n\n\nOkay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\nsnippet = Snippet(code='foo = \"bar\"\\n')\nsnippet.save()\n\nsnippet = Snippet(code='print \"hello, world\"\\n')\nsnippet.save()\n\n\n\nWe've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.\n\n\nserializer = SnippetSerializer(snippet)\nserializer.data\n# {'id': 2, 'title': u'', 'code': u'print \"hello, world\"\\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into \njson\n.\n\n\ncontent = JSONRenderer().render(serializer.data)\ncontent\n# '{\"id\": 2, \"title\": \"\", \"code\": \"print \\\\\"hello, world\\\\\"\\\\n\", \"linenos\": false, \"language\": \"python\", \"style\": \"friendly\"}'\n\n\n\nDeserialization is similar. First we parse a stream into Python native datatypes...\n\n\nfrom django.utils.six import BytesIO\n\nstream = BytesIO(content)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a fully populated object instance.\n\n\nserializer = SnippetSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# OrderedDict([('title', ''), ('code', 'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])\nserializer.save()\n# \nSnippet: Snippet object\n\n\n\n\nNotice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.\n\n\nWe can also serialize querysets instead of model instances. To do so we simply add a \nmany=True\n flag to the serializer arguments.\n\n\nserializer = SnippetSerializer(Snippet.objects.all(), many=True)\nserializer.data\n# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = \"bar\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print \"hello, world\"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]\n\n\n\nUsing ModelSerializers\n\n\nOur \nSnippetSerializer\n class is replicating a lot of information that's also contained in the \nSnippet\n model. It would be nice if we could keep our code a bit more concise.\n\n\nIn the same way that Django provides both \nForm\n classes and \nModelForm\n classes, REST framework includes both \nSerializer\n classes, and \nModelSerializer\n classes.\n\n\nLet's look at refactoring our serializer using the \nModelSerializer\n class.\nOpen the file \nsnippets/serializers.py\n again, and replace the \nSnippetSerializer\n class with the following.\n\n\nclass SnippetSerializer(serializers.ModelSerializer):\n class Meta:\n model = Snippet\n fields = ('id', 'title', 'code', 'linenos', 'language', 'style')\n\n\n\nOne nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with \npython manage.py shell\n, then try the following:\n\n\nfrom snippets.serializers import SnippetSerializer\nserializer = SnippetSerializer()\nprint(repr(serializer))\n# SnippetSerializer():\n# id = IntegerField(label='ID', read_only=True)\n# title = CharField(allow_blank=True, max_length=100, required=False)\n# code = CharField(style={'base_template': 'textarea.html'})\n# linenos = BooleanField(required=False)\n# language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...\n# style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...\n\n\n\nIt's important to remember that \nModelSerializer\n classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:\n\n\n\n\nAn automatically determined set of fields.\n\n\nSimple default implementations for the \ncreate()\n and \nupdate()\n methods.\n\n\n\n\nWriting regular Django views using our Serializer\n\n\nLet's see how we can write some API views using our new Serializer class.\nFor the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.\n\n\nWe'll start off by creating a subclass of HttpResponse that we can use to render any data we return into \njson\n.\n\n\nEdit the \nsnippets/views.py\n file, and add the following.\n\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\nclass JSONResponse(HttpResponse):\n \"\"\"\n An HttpResponse that renders its content into JSON.\n \"\"\"\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super(JSONResponse, self).__init__(content, **kwargs)\n\n\n\nThe root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.\n\n\n@csrf_exempt\ndef snippet_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return JSONResponse(serializer.data)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data, status=201)\n return JSONResponse(serializer.errors, status=400)\n\n\n\nNote that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as \ncsrf_exempt\n. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.\n\n\nWe'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.\n\n\n@csrf_exempt\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = SnippetSerializer(snippet)\n return JSONResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(snippet, data=data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data)\n return JSONResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n snippet.delete()\n return HttpResponse(status=204)\n\n\n\nFinally we need to wire these views up. Create the \nsnippets/urls.py\n file:\n\n\nfrom django.conf.urls import url\nfrom snippets import views\n\nurlpatterns = [\n url(r'^snippets/$', views.snippet_list),\n url(r'^snippets/(?P\npk\n[0-9]+)/$', views.snippet_detail),\n]\n\n\n\nWe also need to wire up the root urlconf, in the \ntutorial/urls.py\n file, to include our snippet app's URLs.\n\n\nfrom django.conf.urls import url, include\n\nurlpatterns = [\n url(r'^', include('snippets.urls')),\n]\n\n\n\nIt's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed \njson\n, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 \"server error\" response. Still, this'll do for now.\n\n\nTesting our first attempt at a Web API\n\n\nNow we can start up a sample server that serves our snippets.\n\n\nQuit out of the shell...\n\n\nquit()\n\n\n\n...and start up Django's development server.\n\n\npython manage.py runserver\n\nValidating models...\n\n0 errors found\nDjango version 1.8.3, using settings 'tutorial.settings'\nDevelopment server is running at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n\n\n\nIn another terminal window, we can test the server.\n\n\nWe can test our API using \ncurl\n or \nhttpie\n. Httpie is a user friendly http client that's written in Python. Let's install that.\n\n\nYou can install httpie using pip:\n\n\npip install httpie\n\n\n\nFinally, we can get a list of all of the snippets:\n\n\nhttp http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print \\\"hello, world\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n]\n\n\n\nOr we can get a particular snippet by referencing its id:\n\n\nhttp http://127.0.0.1:8000/snippets/2/\n\nHTTP/1.1 200 OK\n...\n{\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print \\\"hello, world\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n\n\nSimilarly, you can have the same json displayed by visiting these URLs in a web browser.\n\n\nWhere are we now\n\n\nWe're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.\n\n\nOur API views don't do anything particularly special at the moment, beyond serving \njson\n responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.\n\n\nWe'll see how we can start to improve things in \npart 2 of the tutorial\n.", + "text": "Tutorial 1: Serialization\n\n\nIntroduction\n\n\nThis tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.\n\n\nThe tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the \nquickstart\n documentation instead.\n\n\n\n\nNote\n: The code for this tutorial is available in the \ntomchristie/rest-framework-tutorial\n repository on GitHub. The completed implementation is also online as a sandbox version for testing, \navailable here\n.\n\n\n\n\nSetting up a new environment\n\n\nBefore we do anything else we'll create a new virtual environment, using \nvirtualenv\n. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.\n\n\nvirtualenv env\nsource env/bin/activate\n\n\n\nNow that we're inside a virtualenv environment, we can install our package requirements.\n\n\npip install django\npip install djangorestframework\npip install pygments # We'll be using this for the code highlighting\n\n\n\nNote:\n To exit the virtualenv environment at any time, just type \ndeactivate\n. For more information see the \nvirtualenv documentation\n.\n\n\nGetting started\n\n\nOkay, we're ready to get coding.\nTo get started, let's create a new project to work with.\n\n\ncd ~\ndjango-admin.py startproject tutorial\ncd tutorial\n\n\n\nOnce that's done we can create an app that we'll use to create a simple Web API.\n\n\npython manage.py startapp snippets\n\n\n\nWe'll need to add our new \nsnippets\n app and the \nrest_framework\n app to \nINSTALLED_APPS\n. Let's edit the \ntutorial/settings.py\n file:\n\n\nINSTALLED_APPS = (\n ...\n 'rest_framework',\n 'snippets.apps.SnippetsConfig',\n)\n\n\n\nPlease note that if you're using Django \n1.9, you need to replace \nsnippets.apps.SnippetsConfig\n with \nsnippets\n.\n\n\nOkay, we're ready to roll.\n\n\nCreating a model to work with\n\n\nFor the purposes of this tutorial we're going to start by creating a simple \nSnippet\n model that is used to store code snippets. Go ahead and edit the \nsnippets/models.py\n file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.\n\n\nfrom django.db import models\nfrom pygments.lexers import get_all_lexers\nfrom pygments.styles import get_all_styles\n\nLEXERS = [item for item in get_all_lexers() if item[1]]\nLANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])\nSTYLE_CHOICES = sorted((item, item) for item in get_all_styles())\n\n\nclass Snippet(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n title = models.CharField(max_length=100, blank=True, default='')\n code = models.TextField()\n linenos = models.BooleanField(default=False)\n language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)\n style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)\n\n class Meta:\n ordering = ('created',)\n\n\n\nWe'll also need to create an initial migration for our snippet model, and sync the database for the first time.\n\n\npython manage.py makemigrations snippets\npython manage.py migrate\n\n\n\nCreating a Serializer class\n\n\nThe first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as \njson\n. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the \nsnippets\n directory named \nserializers.py\n and add the following.\n\n\nfrom rest_framework import serializers\nfrom snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES\n\n\nclass SnippetSerializer(serializers.Serializer):\n id = serializers.IntegerField(read_only=True)\n title = serializers.CharField(required=False, allow_blank=True, max_length=100)\n code = serializers.CharField(style={'base_template': 'textarea.html'})\n linenos = serializers.BooleanField(required=False)\n language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')\n style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Snippet` instance, given the validated data.\n \"\"\"\n return Snippet.objects.create(**validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Snippet` instance, given the validated data.\n \"\"\"\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\n\n\nThe first part of the serializer class defines the fields that get serialized/deserialized. The \ncreate()\n and \nupdate()\n methods define how fully fledged instances are created or modified when calling \nserializer.save()\n\n\nA serializer class is very similar to a Django \nForm\n class, and includes similar validation flags on the various fields, such as \nrequired\n, \nmax_length\n and \ndefault\n.\n\n\nThe field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The \n{'base_template': 'textarea.html'}\n flag above is equivalent to using \nwidget=widgets.Textarea\n on a Django \nForm\n class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.\n\n\nWe can actually also save ourselves some time by using the \nModelSerializer\n class, as we'll see later, but for now we'll keep our serializer definition explicit.\n\n\nWorking with Serializers\n\n\nBefore we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.\n\n\npython manage.py shell\n\n\n\nOkay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.\n\n\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\n\nsnippet = Snippet(code='foo = \"bar\"\\n')\nsnippet.save()\n\nsnippet = Snippet(code='print \"hello, world\"\\n')\nsnippet.save()\n\n\n\nWe've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.\n\n\nserializer = SnippetSerializer(snippet)\nserializer.data\n# {'id': 2, 'title': u'', 'code': u'print \"hello, world\"\\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}\n\n\n\nAt this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into \njson\n.\n\n\ncontent = JSONRenderer().render(serializer.data)\ncontent\n# '{\"id\": 2, \"title\": \"\", \"code\": \"print \\\\\"hello, world\\\\\"\\\\n\", \"linenos\": false, \"language\": \"python\", \"style\": \"friendly\"}'\n\n\n\nDeserialization is similar. First we parse a stream into Python native datatypes...\n\n\nfrom django.utils.six import BytesIO\n\nstream = BytesIO(content)\ndata = JSONParser().parse(stream)\n\n\n\n...then we restore those native datatypes into a fully populated object instance.\n\n\nserializer = SnippetSerializer(data=data)\nserializer.is_valid()\n# True\nserializer.validated_data\n# OrderedDict([('title', ''), ('code', 'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])\nserializer.save()\n# \nSnippet: Snippet object\n\n\n\n\nNotice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.\n\n\nWe can also serialize querysets instead of model instances. To do so we simply add a \nmany=True\n flag to the serializer arguments.\n\n\nserializer = SnippetSerializer(Snippet.objects.all(), many=True)\nserializer.data\n# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = \"bar\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print \"hello, world\"\\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print \"hello, world\"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]\n\n\n\nUsing ModelSerializers\n\n\nOur \nSnippetSerializer\n class is replicating a lot of information that's also contained in the \nSnippet\n model. It would be nice if we could keep our code a bit more concise.\n\n\nIn the same way that Django provides both \nForm\n classes and \nModelForm\n classes, REST framework includes both \nSerializer\n classes, and \nModelSerializer\n classes.\n\n\nLet's look at refactoring our serializer using the \nModelSerializer\n class.\nOpen the file \nsnippets/serializers.py\n again, and replace the \nSnippetSerializer\n class with the following.\n\n\nclass SnippetSerializer(serializers.ModelSerializer):\n class Meta:\n model = Snippet\n fields = ('id', 'title', 'code', 'linenos', 'language', 'style')\n\n\n\nOne nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with \npython manage.py shell\n, then try the following:\n\n\nfrom snippets.serializers import SnippetSerializer\nserializer = SnippetSerializer()\nprint(repr(serializer))\n# SnippetSerializer():\n# id = IntegerField(label='ID', read_only=True)\n# title = CharField(allow_blank=True, max_length=100, required=False)\n# code = CharField(style={'base_template': 'textarea.html'})\n# linenos = BooleanField(required=False)\n# language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...\n# style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...\n\n\n\nIt's important to remember that \nModelSerializer\n classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:\n\n\n\n\nAn automatically determined set of fields.\n\n\nSimple default implementations for the \ncreate()\n and \nupdate()\n methods.\n\n\n\n\nWriting regular Django views using our Serializer\n\n\nLet's see how we can write some API views using our new Serializer class.\nFor the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.\n\n\nEdit the \nsnippets/views.py\n file, and add the following.\n\n\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\n\n\nThe root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.\n\n\n@csrf_exempt\ndef snippet_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n\n\nNote that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as \ncsrf_exempt\n. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.\n\n\nWe'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.\n\n\n@csrf_exempt\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = SnippetSerializer(snippet)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(snippet, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n snippet.delete()\n return HttpResponse(status=204)\n\n\n\nFinally we need to wire these views up. Create the \nsnippets/urls.py\n file:\n\n\nfrom django.conf.urls import url\nfrom snippets import views\n\nurlpatterns = [\n url(r'^snippets/$', views.snippet_list),\n url(r'^snippets/(?P\npk\n[0-9]+)/$', views.snippet_detail),\n]\n\n\n\nWe also need to wire up the root urlconf, in the \ntutorial/urls.py\n file, to include our snippet app's URLs.\n\n\nfrom django.conf.urls import url, include\n\nurlpatterns = [\n url(r'^', include('snippets.urls')),\n]\n\n\n\nIt's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed \njson\n, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 \"server error\" response. Still, this'll do for now.\n\n\nTesting our first attempt at a Web API\n\n\nNow we can start up a sample server that serves our snippets.\n\n\nQuit out of the shell...\n\n\nquit()\n\n\n\n...and start up Django's development server.\n\n\npython manage.py runserver\n\nValidating models...\n\n0 errors found\nDjango version 1.8.3, using settings 'tutorial.settings'\nDevelopment server is running at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n\n\n\nIn another terminal window, we can test the server.\n\n\nWe can test our API using \ncurl\n or \nhttpie\n. Httpie is a user friendly http client that's written in Python. Let's install that.\n\n\nYou can install httpie using pip:\n\n\npip install httpie\n\n\n\nFinally, we can get a list of all of the snippets:\n\n\nhttp http://127.0.0.1:8000/snippets/\n\nHTTP/1.1 200 OK\n...\n[\n {\n \"id\": 1,\n \"title\": \"\",\n \"code\": \"foo = \\\"bar\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n },\n {\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print \\\"hello, world\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n }\n]\n\n\n\nOr we can get a particular snippet by referencing its id:\n\n\nhttp http://127.0.0.1:8000/snippets/2/\n\nHTTP/1.1 200 OK\n...\n{\n \"id\": 2,\n \"title\": \"\",\n \"code\": \"print \\\"hello, world\\\"\\n\",\n \"linenos\": false,\n \"language\": \"python\",\n \"style\": \"friendly\"\n}\n\n\n\nSimilarly, you can have the same json displayed by visiting these URLs in a web browser.\n\n\nWhere are we now\n\n\nWe're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.\n\n\nOur API views don't do anything particularly special at the moment, beyond serving \njson\n responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.\n\n\nWe'll see how we can start to improve things in \npart 2 of the tutorial\n.", "title": "1 - Serialization" }, { @@ -152,7 +152,7 @@ }, { "location": "/tutorial/1-serialization/#writing-regular-django-views-using-our-serializer", - "text": "Let's see how we can write some API views using our new Serializer class.\nFor the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views. We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into json . Edit the snippets/views.py file, and add the following. from django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer\n\nclass JSONResponse(HttpResponse):\n \"\"\"\n An HttpResponse that renders its content into JSON.\n \"\"\"\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super(JSONResponse, self).__init__(content, **kwargs) The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. @csrf_exempt\ndef snippet_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return JSONResponse(serializer.data)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data, status=201)\n return JSONResponse(serializer.errors, status=400) Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt . This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now. We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet. @csrf_exempt\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = SnippetSerializer(snippet)\n return JSONResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(snippet, data=data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data)\n return JSONResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n snippet.delete()\n return HttpResponse(status=204) Finally we need to wire these views up. Create the snippets/urls.py file: from django.conf.urls import url\nfrom snippets import views\n\nurlpatterns = [\n url(r'^snippets/$', views.snippet_list),\n url(r'^snippets/(?P pk [0-9]+)/$', views.snippet_detail),\n] We also need to wire up the root urlconf, in the tutorial/urls.py file, to include our snippet app's URLs. from django.conf.urls import url, include\n\nurlpatterns = [\n url(r'^', include('snippets.urls')),\n] It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed json , or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 \"server error\" response. Still, this'll do for now.", + "text": "Let's see how we can write some API views using our new Serializer class.\nFor the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views. Edit the snippets/views.py file, and add the following. from django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom snippets.models import Snippet\nfrom snippets.serializers import SnippetSerializer The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. @csrf_exempt\ndef snippet_list(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets, many=True)\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400) Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt . This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now. We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet. @csrf_exempt\ndef snippet_detail(request, pk):\n \"\"\"\n Retrieve, update or delete a code snippet.\n \"\"\"\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = SnippetSerializer(snippet)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = SnippetSerializer(snippet, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n snippet.delete()\n return HttpResponse(status=204) Finally we need to wire these views up. Create the snippets/urls.py file: from django.conf.urls import url\nfrom snippets import views\n\nurlpatterns = [\n url(r'^snippets/$', views.snippet_list),\n url(r'^snippets/(?P pk [0-9]+)/$', views.snippet_detail),\n] We also need to wire up the root urlconf, in the tutorial/urls.py file, to include our snippet app's URLs. from django.conf.urls import url, include\n\nurlpatterns = [\n url(r'^', include('snippets.urls')),\n] It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed json , or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 \"server error\" response. Still, this'll do for now.", "title": "Writing regular Django views using our Serializer" }, { @@ -717,7 +717,7 @@ }, { "location": "/api-guide/generic-views/", - "text": "Generic views\n\n\n\n\nDjango\u2019s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.\n\n\n \nDjango Documentation\n\n\n\n\nOne of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.\n\n\nThe generic views provided by REST framework allow you to quickly build API views that map closely to your database models.\n\n\nIf the generic views don't suit the needs of your API, you can drop down to using the regular \nAPIView\n class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.\n\n\nExamples\n\n\nTypically when using the generic views, you'll override the view, and set several class attributes.\n\n\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAdminUser\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (IsAdminUser,)\n\n\n\nFor more complex cases you might also want to override various methods on the view class. For example.\n\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (IsAdminUser,)\n\n def list(self, request):\n # Note the use of `get_queryset()` instead of `self.queryset`\n queryset = self.get_queryset()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n\nFor very simple cases you might want to pass through any class attributes using the \n.as_view()\n method. For example, your URLconf might include something like the following entry:\n\n\nurl(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')\n\n\n\n\n\nAPI Reference\n\n\nGenericAPIView\n\n\nThis class extends REST framework's \nAPIView\n class, adding commonly required behavior for standard list and detail views.\n\n\nEach of the concrete generic views provided is built by combining \nGenericAPIView\n, with one or more mixin classes.\n\n\nAttributes\n\n\nBasic settings\n:\n\n\nThe following attributes control the basic view behavior.\n\n\n\n\nqueryset\n - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the \nget_queryset()\n method. If you are overriding a view method, it is important that you call \nget_queryset()\n instead of accessing this property directly, as \nqueryset\n will get evaluated once, and those results will be cached for all subsequent requests.\n\n\nserializer_class\n - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the \nget_serializer_class()\n method.\n\n\nlookup_field\n - The model field that should be used to for performing object lookup of individual model instances. Defaults to \n'pk'\n. Note that when using hyperlinked APIs you'll need to ensure that \nboth\n the API views \nand\n the serializer classes set the lookup fields if you need to use a custom value.\n\n\nlookup_url_kwarg\n - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as \nlookup_field\n.\n\n\n\n\nPagination\n:\n\n\nThe following attributes are used to control pagination when used with list views.\n\n\n\n\npagination_class\n - The pagination class that should be used when paginating list results. Defaults to the same value as the \nDEFAULT_PAGINATION_CLASS\n setting, which is \n'rest_framework.pagination.PageNumberPagination'\n.\n\n\n\n\nFiltering\n:\n\n\n\n\nfilter_backends\n - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the \nDEFAULT_FILTER_BACKENDS\n setting.\n\n\n\n\nMethods\n\n\nBase methods\n:\n\n\nget_queryset(self)\n\n\nReturns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the \nqueryset\n attribute.\n\n\nThis method should always be used rather than accessing \nself.queryset\n directly, as \nself.queryset\n gets evaluated only once, and those results are cached for all subsequent requests.\n\n\nMay be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.\n\n\nFor example:\n\n\ndef get_queryset(self):\n user = self.request.user\n return user.accounts.all()\n\n\n\nget_object(self)\n\n\nReturns an object instance that should be used for detail views. Defaults to using the \nlookup_field\n parameter to filter the base queryset.\n\n\nMay be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.\n\n\nFor example:\n\n\ndef get_object(self):\n queryset = self.get_queryset()\n filter = {}\n for field in self.multiple_lookup_fields:\n filter[field] = self.kwargs[field]\n\n obj = get_object_or_404(queryset, **filter)\n self.check_object_permissions(self.request, obj)\n return obj\n\n\n\nNote that if your API doesn't include any object level permissions, you may optionally exclude the \nself.check_object_permissions\n, and simply return the object from the \nget_object_or_404\n lookup.\n\n\nfilter_queryset(self, queryset)\n\n\nGiven a queryset, filter it with whichever filter backends are in use, returning a new queryset. \n\n\nFor example: \n\n\ndef filter_queryset(self, queryset):\n filter_backends = (CategoryFilter,)\n\n if 'geo_route' in self.request.query_params:\n filter_backends = (GeoRouteFilter, CategoryFilter)\n elif 'geo_point' in self.request.query_params:\n filter_backends = (GeoPointFilter, CategoryFilter)\n\n for backend in list(filter_backends):\n queryset = backend().filter_queryset(self.request, queryset, view=self)\n\n return queryset\n\n\n\nget_serializer_class(self)\n\n\nReturns the class that should be used for the serializer. Defaults to returning the \nserializer_class\n attribute.\n\n\nMay be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.\n\n\nFor example:\n\n\ndef get_serializer_class(self):\n if self.request.user.is_staff:\n return FullAccountSerializer\n return BasicAccountSerializer\n\n\n\nSave and deletion hooks\n:\n\n\nThe following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.\n\n\n\n\nperform_create(self, serializer)\n - Called by \nCreateModelMixin\n when saving a new object instance.\n\n\nperform_update(self, serializer)\n - Called by \nUpdateModelMixin\n when saving an existing object instance.\n\n\nperform_destroy(self, instance)\n - Called by \nDestroyModelMixin\n when deleting an object instance.\n\n\n\n\nThese hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.\n\n\ndef perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\n\nThese override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.\n\n\ndef perform_update(self, serializer):\n instance = serializer.save()\n send_email_confirmation(user=self.request.user, modified=instance)\n\n\n\nYou can also use these hooks to provide additional validation, by raising a \nValidationError()\n. This can be useful if you need some validation logic to apply at the point of database save. For example:\n\n\ndef perform_create(self, serializer):\n queryset = SignupRequest.objects.filter(user=self.request.user)\n if queryset.exists():\n raise ValidationError('You have already signed up')\n serializer.save(user=self.request.user)\n\n\n\nNote\n: These methods replace the old-style version 2.x \npre_save\n, \npost_save\n, \npre_delete\n and \npost_delete\n methods, which are no longer available.\n\n\nOther methods\n:\n\n\nYou won't typically need to override the following methods, although you might need to call into them if you're writing custom views using \nGenericAPIView\n.\n\n\n\n\nget_serializer_context(self)\n - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including \n'request'\n, \n'view'\n and \n'format'\n keys.\n\n\nget_serializer(self, instance=None, data=None, many=False, partial=False)\n - Returns a serializer instance.\n\n\nget_paginated_response(self, data)\n - Returns a paginated style \nResponse\n object.\n\n\npaginate_queryset(self, queryset)\n - Paginate a queryset if required, either returning a page object, or \nNone\n if pagination is not configured for this view.\n\n\nfilter_queryset(self, queryset)\n - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.\n\n\n\n\n\n\nMixins\n\n\nThe mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as \n.get()\n and \n.post()\n, directly. This allows for more flexible composition of behavior.\n\n\nThe mixin classes can be imported from \nrest_framework.mixins\n.\n\n\nListModelMixin\n\n\nProvides a \n.list(request, *args, **kwargs)\n method, that implements listing a queryset.\n\n\nIf the queryset is populated, this returns a \n200 OK\n response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.\n\n\nCreateModelMixin\n\n\nProvides a \n.create(request, *args, **kwargs)\n method, that implements creating and saving a new model instance.\n\n\nIf an object is created this returns a \n201 Created\n response, with a serialized representation of the object as the body of the response. If the representation contains a key named \nurl\n, then the \nLocation\n header of the response will be populated with that value.\n\n\nIf the request data provided for creating the object was invalid, a \n400 Bad Request\n response will be returned, with the error details as the body of the response.\n\n\nRetrieveModelMixin\n\n\nProvides a \n.retrieve(request, *args, **kwargs)\n method, that implements returning an existing model instance in a response.\n\n\nIf an object can be retrieved this returns a \n200 OK\n response, with a serialized representation of the object as the body of the response. Otherwise it will return a \n404 Not Found\n.\n\n\nUpdateModelMixin\n\n\nProvides a \n.update(request, *args, **kwargs)\n method, that implements updating and saving an existing model instance.\n\n\nAlso provides a \n.partial_update(request, *args, **kwargs)\n method, which is similar to the \nupdate\n method, except that all fields for the update will be optional. This allows support for HTTP \nPATCH\n requests.\n\n\nIf an object is updated this returns a \n200 OK\n response, with a serialized representation of the object as the body of the response.\n\n\nIf the request data provided for updating the object was invalid, a \n400 Bad Request\n response will be returned, with the error details as the body of the response.\n\n\nDestroyModelMixin\n\n\nProvides a \n.destroy(request, *args, **kwargs)\n method, that implements deletion of an existing model instance.\n\n\nIf an object is deleted this returns a \n204 No Content\n response, otherwise it will return a \n404 Not Found\n.\n\n\n\n\nConcrete View Classes\n\n\nThe following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.\n\n\nThe view classes can be imported from \nrest_framework.generics\n.\n\n\nCreateAPIView\n\n\nUsed for \ncreate-only\n endpoints.\n\n\nProvides a \npost\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nCreateModelMixin\n\n\nListAPIView\n\n\nUsed for \nread-only\n endpoints to represent a \ncollection of model instances\n.\n\n\nProvides a \nget\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nListModelMixin\n\n\nRetrieveAPIView\n\n\nUsed for \nread-only\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides a \nget\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n\n\nDestroyAPIView\n\n\nUsed for \ndelete-only\n endpoints for a \nsingle model instance\n.\n\n\nProvides a \ndelete\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nDestroyModelMixin\n\n\nUpdateAPIView\n\n\nUsed for \nupdate-only\n endpoints for a \nsingle model instance\n.\n\n\nProvides \nput\n and \npatch\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nUpdateModelMixin\n\n\nListCreateAPIView\n\n\nUsed for \nread-write\n endpoints to represent a \ncollection of model instances\n.\n\n\nProvides \nget\n and \npost\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nListModelMixin\n, \nCreateModelMixin\n\n\nRetrieveUpdateAPIView\n\n\nUsed for \nread or update\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n, \nput\n and \npatch\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nUpdateModelMixin\n\n\nRetrieveDestroyAPIView\n\n\nUsed for \nread or delete\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n and \ndelete\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nDestroyModelMixin\n\n\nRetrieveUpdateDestroyAPIView\n\n\nUsed for \nread-write-delete\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n, \nput\n, \npatch\n and \ndelete\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nUpdateModelMixin\n, \nDestroyModelMixin\n\n\n\n\nCustomizing the generic views\n\n\nOften you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.\n\n\nCreating custom mixins\n\n\nFor example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:\n\n\nclass MultipleFieldLookupMixin(object):\n \"\"\"\n Apply this mixin to any view or viewset to get multiple field filtering\n based on a `lookup_fields` attribute, instead of the default single field filtering.\n \"\"\"\n def get_object(self):\n queryset = self.get_queryset() # Get the base queryset\n queryset = self.filter_queryset(queryset) # Apply any filter backends\n filter = {}\n for field in self.lookup_fields:\n if self.kwargs[field]: # Ignore empty fields.\n filter[field] = self.kwargs[field]\n return get_object_or_404(queryset, **filter) # Lookup the object\n\n\n\nYou can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.\n\n\nclass RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_fields = ('account', 'username')\n\n\n\nUsing custom mixins is a good option if you have custom behavior that needs to be used.\n\n\nCreating custom base classes\n\n\nIf you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:\n\n\nclass BaseRetrieveView(MultipleFieldLookupMixin,\n generics.RetrieveAPIView):\n pass\n\nclass BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,\n generics.RetrieveUpdateDestroyAPIView):\n pass\n\n\n\nUsing custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.\n\n\n\n\nPUT as create\n\n\nPrior to version 3.0 the REST framework mixins treated \nPUT\n as either an update or a create operation, depending on if the object already existed or not.\n\n\nAllowing \nPUT\n as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n as create\" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.\n\n\nIf you need to generic PUT-as-create behavior you may want to include something like \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\n\n\nThird party packages\n\n\nThe following third party packages provide additional generic view implementations.\n\n\nDjango REST Framework bulk\n\n\nThe \ndjango-rest-framework-bulk package\n implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\nDjango Rest Multiple Models\n\n\nDjango Rest Multiple Models\n provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.", + "text": "Generic views\n\n\n\n\nDjango\u2019s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.\n\n\n \nDjango Documentation\n\n\n\n\nOne of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.\n\n\nThe generic views provided by REST framework allow you to quickly build API views that map closely to your database models.\n\n\nIf the generic views don't suit the needs of your API, you can drop down to using the regular \nAPIView\n class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.\n\n\nExamples\n\n\nTypically when using the generic views, you'll override the view, and set several class attributes.\n\n\nfrom django.contrib.auth.models import User\nfrom myapp.serializers import UserSerializer\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAdminUser\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (IsAdminUser,)\n\n\n\nFor more complex cases you might also want to override various methods on the view class. For example.\n\n\nclass UserList(generics.ListCreateAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (IsAdminUser,)\n\n def list(self, request):\n # Note the use of `get_queryset()` instead of `self.queryset`\n queryset = self.get_queryset()\n serializer = UserSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n\nFor very simple cases you might want to pass through any class attributes using the \n.as_view()\n method. For example, your URLconf might include something like the following entry:\n\n\nurl(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')\n\n\n\n\n\nAPI Reference\n\n\nGenericAPIView\n\n\nThis class extends REST framework's \nAPIView\n class, adding commonly required behavior for standard list and detail views.\n\n\nEach of the concrete generic views provided is built by combining \nGenericAPIView\n, with one or more mixin classes.\n\n\nAttributes\n\n\nBasic settings\n:\n\n\nThe following attributes control the basic view behavior.\n\n\n\n\nqueryset\n - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the \nget_queryset()\n method. If you are overriding a view method, it is important that you call \nget_queryset()\n instead of accessing this property directly, as \nqueryset\n will get evaluated once, and those results will be cached for all subsequent requests.\n\n\nserializer_class\n - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the \nget_serializer_class()\n method.\n\n\nlookup_field\n - The model field that should be used to for performing object lookup of individual model instances. Defaults to \n'pk'\n. Note that when using hyperlinked APIs you'll need to ensure that \nboth\n the API views \nand\n the serializer classes set the lookup fields if you need to use a custom value.\n\n\nlookup_url_kwarg\n - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as \nlookup_field\n.\n\n\n\n\nPagination\n:\n\n\nThe following attributes are used to control pagination when used with list views.\n\n\n\n\npagination_class\n - The pagination class that should be used when paginating list results. Defaults to the same value as the \nDEFAULT_PAGINATION_CLASS\n setting, which is \n'rest_framework.pagination.PageNumberPagination'\n. Setting \npagination_class=None\n will disable pagination on this view.\n\n\n\n\nFiltering\n:\n\n\n\n\nfilter_backends\n - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the \nDEFAULT_FILTER_BACKENDS\n setting.\n\n\n\n\nMethods\n\n\nBase methods\n:\n\n\nget_queryset(self)\n\n\nReturns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the \nqueryset\n attribute.\n\n\nThis method should always be used rather than accessing \nself.queryset\n directly, as \nself.queryset\n gets evaluated only once, and those results are cached for all subsequent requests.\n\n\nMay be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.\n\n\nFor example:\n\n\ndef get_queryset(self):\n user = self.request.user\n return user.accounts.all()\n\n\n\nget_object(self)\n\n\nReturns an object instance that should be used for detail views. Defaults to using the \nlookup_field\n parameter to filter the base queryset.\n\n\nMay be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.\n\n\nFor example:\n\n\ndef get_object(self):\n queryset = self.get_queryset()\n filter = {}\n for field in self.multiple_lookup_fields:\n filter[field] = self.kwargs[field]\n\n obj = get_object_or_404(queryset, **filter)\n self.check_object_permissions(self.request, obj)\n return obj\n\n\n\nNote that if your API doesn't include any object level permissions, you may optionally exclude the \nself.check_object_permissions\n, and simply return the object from the \nget_object_or_404\n lookup.\n\n\nfilter_queryset(self, queryset)\n\n\nGiven a queryset, filter it with whichever filter backends are in use, returning a new queryset. \n\n\nFor example: \n\n\ndef filter_queryset(self, queryset):\n filter_backends = (CategoryFilter,)\n\n if 'geo_route' in self.request.query_params:\n filter_backends = (GeoRouteFilter, CategoryFilter)\n elif 'geo_point' in self.request.query_params:\n filter_backends = (GeoPointFilter, CategoryFilter)\n\n for backend in list(filter_backends):\n queryset = backend().filter_queryset(self.request, queryset, view=self)\n\n return queryset\n\n\n\nget_serializer_class(self)\n\n\nReturns the class that should be used for the serializer. Defaults to returning the \nserializer_class\n attribute.\n\n\nMay be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.\n\n\nFor example:\n\n\ndef get_serializer_class(self):\n if self.request.user.is_staff:\n return FullAccountSerializer\n return BasicAccountSerializer\n\n\n\nSave and deletion hooks\n:\n\n\nThe following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.\n\n\n\n\nperform_create(self, serializer)\n - Called by \nCreateModelMixin\n when saving a new object instance.\n\n\nperform_update(self, serializer)\n - Called by \nUpdateModelMixin\n when saving an existing object instance.\n\n\nperform_destroy(self, instance)\n - Called by \nDestroyModelMixin\n when deleting an object instance.\n\n\n\n\nThese hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.\n\n\ndef perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\n\nThese override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.\n\n\ndef perform_update(self, serializer):\n instance = serializer.save()\n send_email_confirmation(user=self.request.user, modified=instance)\n\n\n\nYou can also use these hooks to provide additional validation, by raising a \nValidationError()\n. This can be useful if you need some validation logic to apply at the point of database save. For example:\n\n\ndef perform_create(self, serializer):\n queryset = SignupRequest.objects.filter(user=self.request.user)\n if queryset.exists():\n raise ValidationError('You have already signed up')\n serializer.save(user=self.request.user)\n\n\n\nNote\n: These methods replace the old-style version 2.x \npre_save\n, \npost_save\n, \npre_delete\n and \npost_delete\n methods, which are no longer available.\n\n\nOther methods\n:\n\n\nYou won't typically need to override the following methods, although you might need to call into them if you're writing custom views using \nGenericAPIView\n.\n\n\n\n\nget_serializer_context(self)\n - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including \n'request'\n, \n'view'\n and \n'format'\n keys.\n\n\nget_serializer(self, instance=None, data=None, many=False, partial=False)\n - Returns a serializer instance.\n\n\nget_paginated_response(self, data)\n - Returns a paginated style \nResponse\n object.\n\n\npaginate_queryset(self, queryset)\n - Paginate a queryset if required, either returning a page object, or \nNone\n if pagination is not configured for this view.\n\n\nfilter_queryset(self, queryset)\n - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.\n\n\n\n\n\n\nMixins\n\n\nThe mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as \n.get()\n and \n.post()\n, directly. This allows for more flexible composition of behavior.\n\n\nThe mixin classes can be imported from \nrest_framework.mixins\n.\n\n\nListModelMixin\n\n\nProvides a \n.list(request, *args, **kwargs)\n method, that implements listing a queryset.\n\n\nIf the queryset is populated, this returns a \n200 OK\n response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.\n\n\nCreateModelMixin\n\n\nProvides a \n.create(request, *args, **kwargs)\n method, that implements creating and saving a new model instance.\n\n\nIf an object is created this returns a \n201 Created\n response, with a serialized representation of the object as the body of the response. If the representation contains a key named \nurl\n, then the \nLocation\n header of the response will be populated with that value.\n\n\nIf the request data provided for creating the object was invalid, a \n400 Bad Request\n response will be returned, with the error details as the body of the response.\n\n\nRetrieveModelMixin\n\n\nProvides a \n.retrieve(request, *args, **kwargs)\n method, that implements returning an existing model instance in a response.\n\n\nIf an object can be retrieved this returns a \n200 OK\n response, with a serialized representation of the object as the body of the response. Otherwise it will return a \n404 Not Found\n.\n\n\nUpdateModelMixin\n\n\nProvides a \n.update(request, *args, **kwargs)\n method, that implements updating and saving an existing model instance.\n\n\nAlso provides a \n.partial_update(request, *args, **kwargs)\n method, which is similar to the \nupdate\n method, except that all fields for the update will be optional. This allows support for HTTP \nPATCH\n requests.\n\n\nIf an object is updated this returns a \n200 OK\n response, with a serialized representation of the object as the body of the response.\n\n\nIf the request data provided for updating the object was invalid, a \n400 Bad Request\n response will be returned, with the error details as the body of the response.\n\n\nDestroyModelMixin\n\n\nProvides a \n.destroy(request, *args, **kwargs)\n method, that implements deletion of an existing model instance.\n\n\nIf an object is deleted this returns a \n204 No Content\n response, otherwise it will return a \n404 Not Found\n.\n\n\n\n\nConcrete View Classes\n\n\nThe following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.\n\n\nThe view classes can be imported from \nrest_framework.generics\n.\n\n\nCreateAPIView\n\n\nUsed for \ncreate-only\n endpoints.\n\n\nProvides a \npost\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nCreateModelMixin\n\n\nListAPIView\n\n\nUsed for \nread-only\n endpoints to represent a \ncollection of model instances\n.\n\n\nProvides a \nget\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nListModelMixin\n\n\nRetrieveAPIView\n\n\nUsed for \nread-only\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides a \nget\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n\n\nDestroyAPIView\n\n\nUsed for \ndelete-only\n endpoints for a \nsingle model instance\n.\n\n\nProvides a \ndelete\n method handler.\n\n\nExtends: \nGenericAPIView\n, \nDestroyModelMixin\n\n\nUpdateAPIView\n\n\nUsed for \nupdate-only\n endpoints for a \nsingle model instance\n.\n\n\nProvides \nput\n and \npatch\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nUpdateModelMixin\n\n\nListCreateAPIView\n\n\nUsed for \nread-write\n endpoints to represent a \ncollection of model instances\n.\n\n\nProvides \nget\n and \npost\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nListModelMixin\n, \nCreateModelMixin\n\n\nRetrieveUpdateAPIView\n\n\nUsed for \nread or update\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n, \nput\n and \npatch\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nUpdateModelMixin\n\n\nRetrieveDestroyAPIView\n\n\nUsed for \nread or delete\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n and \ndelete\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nDestroyModelMixin\n\n\nRetrieveUpdateDestroyAPIView\n\n\nUsed for \nread-write-delete\n endpoints to represent a \nsingle model instance\n.\n\n\nProvides \nget\n, \nput\n, \npatch\n and \ndelete\n method handlers.\n\n\nExtends: \nGenericAPIView\n, \nRetrieveModelMixin\n, \nUpdateModelMixin\n, \nDestroyModelMixin\n\n\n\n\nCustomizing the generic views\n\n\nOften you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.\n\n\nCreating custom mixins\n\n\nFor example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:\n\n\nclass MultipleFieldLookupMixin(object):\n \"\"\"\n Apply this mixin to any view or viewset to get multiple field filtering\n based on a `lookup_fields` attribute, instead of the default single field filtering.\n \"\"\"\n def get_object(self):\n queryset = self.get_queryset() # Get the base queryset\n queryset = self.filter_queryset(queryset) # Apply any filter backends\n filter = {}\n for field in self.lookup_fields:\n if self.kwargs[field]: # Ignore empty fields.\n filter[field] = self.kwargs[field]\n return get_object_or_404(queryset, **filter) # Lookup the object\n\n\n\nYou can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.\n\n\nclass RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n lookup_fields = ('account', 'username')\n\n\n\nUsing custom mixins is a good option if you have custom behavior that needs to be used.\n\n\nCreating custom base classes\n\n\nIf you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:\n\n\nclass BaseRetrieveView(MultipleFieldLookupMixin,\n generics.RetrieveAPIView):\n pass\n\nclass BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,\n generics.RetrieveUpdateDestroyAPIView):\n pass\n\n\n\nUsing custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.\n\n\n\n\nPUT as create\n\n\nPrior to version 3.0 the REST framework mixins treated \nPUT\n as either an update or a create operation, depending on if the object already existed or not.\n\n\nAllowing \nPUT\n as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n as create\" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.\n\n\nIf you need to generic PUT-as-create behavior you may want to include something like \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\n\n\nThird party packages\n\n\nThe following third party packages provide additional generic view implementations.\n\n\nDjango REST Framework bulk\n\n\nThe \ndjango-rest-framework-bulk package\n implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.\n\n\nDjango Rest Multiple Models\n\n\nDjango Rest Multiple Models\n provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.", "title": "Generic views" }, { @@ -742,7 +742,7 @@ }, { "location": "/api-guide/generic-views/#attributes", - "text": "Basic settings : The following attributes control the basic view behavior. queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests. serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method. lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk' . Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value. lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field . Pagination : The following attributes are used to control pagination when used with list views. pagination_class - The pagination class that should be used when paginating list results. Defaults to the same value as the DEFAULT_PAGINATION_CLASS setting, which is 'rest_framework.pagination.PageNumberPagination' . Filtering : filter_backends - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the DEFAULT_FILTER_BACKENDS setting.", + "text": "Basic settings : The following attributes control the basic view behavior. queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests. serializer_class - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the get_serializer_class() method. lookup_field - The model field that should be used to for performing object lookup of individual model instances. Defaults to 'pk' . Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value. lookup_url_kwarg - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as lookup_field . Pagination : The following attributes are used to control pagination when used with list views. pagination_class - The pagination class that should be used when paginating list results. Defaults to the same value as the DEFAULT_PAGINATION_CLASS setting, which is 'rest_framework.pagination.PageNumberPagination' . Setting pagination_class=None will disable pagination on this view. Filtering : filter_backends - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the DEFAULT_FILTER_BACKENDS setting.", "title": "Attributes" }, { @@ -1737,7 +1737,7 @@ }, { "location": "/api-guide/fields/", - "text": "Serializer fields\n\n\n\n\nEach field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \n normalizing it to a consistent format.\n\n\n \nDjango documentation\n\n\n\n\nSerializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.\n\n\n\n\nNote:\n The serializer fields are declared in \nfields.py\n, but by convention you should import them using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nCore arguments\n\n\nEach serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:\n\n\nread_only\n\n\nRead-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.\n\n\nSet this to \nTrue\n to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.\n\n\nDefaults to \nFalse\n\n\nwrite_only\n\n\nSet this to \nTrue\n to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.\n\n\nDefaults to \nFalse\n\n\nrequired\n\n\nNormally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization.\n\n\nSetting this to \nFalse\n also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.\n\n\nDefaults to \nTrue\n.\n\n\nallow_null\n\n\nNormally an error will be raised if \nNone\n is passed to a serializer field. Set this keyword argument to \nTrue\n if \nNone\n should be considered a valid value.\n\n\nDefaults to \nFalse\n\n\ndefault\n\n\nIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.\n\n\nThe \ndefault\n is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.\n\n\nMay be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a \nset_context\n method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for \nvalidators\n.\n\n\nNote that setting a \ndefault\n value implies that the field is not required. Including both the \ndefault\n and \nrequired\n keyword arguments is invalid and will raise an error.\n\n\nsource\n\n\nThe name of the attribute that will be used to populate the field. May be a method that only takes a \nself\n argument, such as \nURLField(source='get_absolute_url')\n, or may use dotted notation to traverse attributes, such as \nEmailField(source='user.email')\n.\n\n\nThe value \nsource='*'\n has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.\n\n\nDefaults to the name of the field.\n\n\nvalidators\n\n\nA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise \nserializers.ValidationError\n, but Django's built-in \nValidationError\n is also supported for compatibility with validators defined in the Django codebase or third party Django packages.\n\n\nerror_messages\n\n\nA dictionary of error codes to error messages.\n\n\nlabel\n\n\nA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.\n\n\nhelp_text\n\n\nA text string that may be used as a description of the field in HTML form fields or other descriptive elements.\n\n\ninitial\n\n\nA value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as\nyou may do with any regular Django \nField\n:\n\n\nimport datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today)\n\n\n\nstyle\n\n\nA dictionary of key-value pairs that can be used to control how renderers should render the field.\n\n\nTwo examples here are \n'input_type'\n and \n'base_template'\n:\n\n\n# Use \ninput type=\"password\"\n for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue'],\n style={'base_template': 'radio.html'}\n)\n\n\n\nFor more details see the \nHTML \n Forms\n documentation.\n\n\n\n\nBoolean fields\n\n\nBooleanField\n\n\nA boolean representation.\n\n\nWhen using HTML encoded form input be aware that omitting a value will always be treated as setting a field to \nFalse\n, even if it has a \ndefault=True\n option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.\n\n\nCorresponds to \ndjango.db.models.fields.BooleanField\n.\n\n\nSignature:\n \nBooleanField()\n\n\nNullBooleanField\n\n\nA boolean representation that also accepts \nNone\n as a valid value.\n\n\nCorresponds to \ndjango.db.models.fields.NullBooleanField\n.\n\n\nSignature:\n \nNullBooleanField()\n\n\n\n\nString fields\n\n\nCharField\n\n\nA text representation. Optionally validates the text to be shorter than \nmax_length\n and longer than \nmin_length\n.\n\n\nCorresponds to \ndjango.db.models.fields.CharField\n or \ndjango.db.models.fields.TextField\n.\n\n\nSignature:\n \nCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)\n\n\n\n\nmax_length\n - Validates that the input contains no more than this number of characters.\n\n\nmin_length\n - Validates that the input contains no fewer than this number of characters.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\ntrim_whitespace\n - If set to \nTrue\n then leading and trailing whitespace is trimmed. Defaults to \nTrue\n.\n\n\n\n\nThe \nallow_null\n option is also available for string fields, although its usage is discouraged in favor of \nallow_blank\n. It is valid to set both \nallow_blank=True\n and \nallow_null=True\n, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.\n\n\nEmailField\n\n\nA text representation, validates the text to be a valid e-mail address.\n\n\nCorresponds to \ndjango.db.models.fields.EmailField\n\n\nSignature:\n \nEmailField(max_length=None, min_length=None, allow_blank=False)\n\n\nRegexField\n\n\nA text representation, that validates the given value matches against a certain regular expression.\n\n\nCorresponds to \ndjango.forms.fields.RegexField\n.\n\n\nSignature:\n \nRegexField(regex, max_length=None, min_length=None, allow_blank=False)\n\n\nThe mandatory \nregex\n argument may either be a string, or a compiled python regular expression object.\n\n\nUses Django's \ndjango.core.validators.RegexValidator\n for validation.\n\n\nSlugField\n\n\nA \nRegexField\n that validates the input against the pattern \n[a-zA-Z0-9_-]+\n.\n\n\nCorresponds to \ndjango.db.models.fields.SlugField\n.\n\n\nSignature:\n \nSlugField(max_length=50, min_length=None, allow_blank=False)\n\n\nURLField\n\n\nA \nRegexField\n that validates the input against a URL matching pattern. Expects fully qualified URLs of the form \nhttp://\nhost\n/\npath\n.\n\n\nCorresponds to \ndjango.db.models.fields.URLField\n. Uses Django's \ndjango.core.validators.URLValidator\n for validation.\n\n\nSignature:\n \nURLField(max_length=200, min_length=None, allow_blank=False)\n\n\nUUIDField\n\n\nA field that ensures the input is a valid UUID string. The \nto_internal_value\n method will return a \nuuid.UUID\n instance. On output the field will return a string in the canonical hyphenated format, for example:\n\n\n\"de305d54-75b4-431b-adb2-eb6b9e546013\"\n\n\n\nSignature:\n \nUUIDField(format='hex_verbose')\n\n\n\n\nformat\n: Determines the representation format of the uuid value\n\n\n'hex_verbose'\n - The cannoncical hex representation, including hyphens: \n\"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n\n'hex'\n - The compact hex representation of the UUID, not including hyphens: \n\"5ce0e9a55ffa654bcee01238041fb31a\"\n\n\n'int'\n - A 128 bit integer representation of the UUID: \n\"123456789012312313134124512351145145114\"\n\n\n'urn'\n - RFC 4122 URN representation of the UUID: \n\"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n Changing the \nformat\n parameters only affects representation values. All formats are accepted by \nto_internal_value\n\n\n\n\n\n\n\n\nFilePathField\n\n\nA field whose choices are limited to the filenames in a certain directory on the filesystem\n\n\nCorresponds to \ndjango.forms.fields.FilePathField\n.\n\n\nSignature:\n \nFilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)\n\n\n\n\npath\n - The absolute filesystem path to a directory from which this FilePathField should get its choice.\n\n\nmatch\n - A regular expression, as a string, that FilePathField will use to filter filenames.\n\n\nrecursive\n - Specifies whether all subdirectories of path should be included. Default is \nFalse\n.\n\n\nallow_files\n - Specifies whether files in the specified location should be included. Default is \nTrue\n. Either this or \nallow_folders\n must be \nTrue\n.\n\n\nallow_folders\n - Specifies whether folders in the specified location should be included. Default is \nFalse\n. Either this or \nallow_files\n must be \nTrue\n.\n\n\n\n\nIPAddressField\n\n\nA field that ensures the input is a valid IPv4 or IPv6 string.\n\n\nCorresponds to \ndjango.forms.fields.IPAddressField\n and \ndjango.forms.fields.GenericIPAddressField\n.\n\n\nSignature\n: \nIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\n\n\n\nprotocol\n Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.\n\n\nunpack_ipv4\n Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.\n\n\n\n\n\n\nNumeric fields\n\n\nIntegerField\n\n\nAn integer representation.\n\n\nCorresponds to \ndjango.db.models.fields.IntegerField\n, \ndjango.db.models.fields.SmallIntegerField\n, \ndjango.db.models.fields.PositiveIntegerField\n and \ndjango.db.models.fields.PositiveSmallIntegerField\n.\n\n\nSignature\n: \nIntegerField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nFloatField\n\n\nA floating point representation.\n\n\nCorresponds to \ndjango.db.models.fields.FloatField\n.\n\n\nSignature\n: \nFloatField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nDecimalField\n\n\nA decimal representation, represented in Python by a \nDecimal\n instance.\n\n\nCorresponds to \ndjango.db.models.fields.DecimalField\n.\n\n\nSignature\n: \nDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)\n\n\n\n\nmax_digits\n The maximum number of digits allowed in the number. It must be either \nNone\n or an integer greater than or equal to \ndecimal_places\n.\n\n\ndecimal_places\n The number of decimal places to store with the number.\n\n\ncoerce_to_string\n Set to \nTrue\n if string values should be returned for the representation, or \nFalse\n if \nDecimal\n objects should be returned. Defaults to the same value as the \nCOERCE_DECIMAL_TO_STRING\n settings key, which will be \nTrue\n unless overridden. If \nDecimal\n objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting \nlocalize\n will force the value to \nTrue\n.\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\nlocalize\n Set to \nTrue\n to enable localization of input and output based on the current locale. This will also force \ncoerce_to_string\n to \nTrue\n. Defaults to \nFalse\n. Note that data formatting is enabled if you have set \nUSE_L10N=True\n in your settings file.\n\n\n\n\nExample usage\n\n\nTo validate numbers up to 999 with a resolution of 2 decimal places, you would use:\n\n\nserializers.DecimalField(max_digits=5, decimal_places=2)\n\n\n\nAnd to validate numbers up to anything less than one billion with a resolution of 10 decimal places:\n\n\nserializers.DecimalField(max_digits=19, decimal_places=10)\n\n\n\nThis field also takes an optional argument, \ncoerce_to_string\n. If set to \nTrue\n the representation will be output as a string. If set to \nFalse\n the representation will be left as a \nDecimal\n instance and the final representation will be determined by the renderer.\n\n\nIf unset, this will default to the same value as the \nCOERCE_DECIMAL_TO_STRING\n setting, which is \nTrue\n unless set otherwise.\n\n\n\n\nDate and time fields\n\n\nDateTimeField\n\n\nA date and time representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateTimeField\n.\n\n\nSignature:\n \nDateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATETIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndatetime\n objects should be returned by \nto_representation\n. In this case the datetime encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATETIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateTimeField\n format strings.\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style datetimes should be used. (eg \n'2013-01-29T12:34:56.000000Z'\n)\n\n\nWhen a value of \nNone\n is used for the format \ndatetime\n objects will be returned by \nto_representation\n and the final output representation will determined by the renderer class.\n\n\nauto_now_add\n model fields.\nauto_now\n and \n\n\nWhen using \nModelSerializer\n or \nHyperlinkedModelSerializer\n, note that any model fields with \nauto_now=True\n or \nauto_now_add=True\n will use serializer fields that are \nread_only=True\n by default.\n\n\nIf you want to override this behavior, you'll need to declare the \nDateTimeField\n explicitly on the serializer. For example:\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment\n\n\n\nDateField\n\n\nA date representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateField\n\n\nSignature:\n \nDateField(format=api_settings.DATE_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATE_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndate\n objects should be returned by \nto_representation\n. In this case the date encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATE_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style dates should be used. (eg \n'2013-01-29'\n)\n\n\nTimeField\n\n\nA time representation.\n\n\nCorresponds to \ndjango.db.models.fields.TimeField\n\n\nSignature:\n \nTimeField(format=api_settings.TIME_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nTIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ntime\n objects should be returned by \nto_representation\n. In this case the time encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nTIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nTimeField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style times should be used. (eg \n'12:34:56.000000'\n)\n\n\nDurationField\n\n\nA Duration representation.\nCorresponds to \ndjango.db.models.fields.DurationField\n\n\nThe \nvalidated_data\n for these fields will contain a \ndatetime.timedelta\n instance.\nThe representation is a string following this format \n'[DD] [HH:[MM:]]ss[.uuuuuu]'\n.\n\n\nNote:\n This field is only available with Django versions \n= 1.8.\n\n\nSignature:\n \nDurationField()\n\n\n\n\nChoice selection fields\n\n\nChoiceField\n\n\nA field that can accept a value out of a limited set of choices.\n\n\nUsed by \nModelSerializer\n to automatically generate fields if the corresponding model field includes a \nchoices=\u2026\n argument.\n\n\nSignature:\n \nChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nBoth the \nallow_blank\n and \nallow_null\n are valid options on \nChoiceField\n, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\nMultipleChoiceField\n\n\nA field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. \nto_internal_value\n returns a \nset\n containing the selected values.\n\n\nSignature:\n \nMultipleChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nAs with \nChoiceField\n, both the \nallow_blank\n and \nallow_null\n options are valid, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\n\n\nFile upload fields\n\n\nParsers and file uploads.\n\n\nThe \nFileField\n and \nImageField\n classes are only suitable for use with \nMultiPartParser\n or \nFileUploadParser\n. Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular \nFILE_UPLOAD_HANDLERS\n are used for handling uploaded files.\n\n\nFileField\n\n\nA file representation. Performs Django's standard FileField validation.\n\n\nCorresponds to \ndjango.forms.fields.FileField\n.\n\n\nSignature:\n \nFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nImageField\n\n\nAn image representation. Validates the uploaded file content as matching a known image format.\n\n\nCorresponds to \ndjango.forms.fields.ImageField\n.\n\n\nSignature:\n \nImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nRequires either the \nPillow\n package or \nPIL\n package. The \nPillow\n package is recommended, as \nPIL\n is no longer actively maintained.\n\n\n\n\nComposite fields\n\n\nListField\n\n\nA field class that validates a list of objects.\n\n\nSignature\n: \nListField(child, min_length=None, max_length=None)\n\n\n\n\nchild\n - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.\n\n\nmin_length\n - Validates that the list contains no fewer than this number of elements.\n\n\nmax_length\n - Validates that the list contains no more than this number of elements.\n\n\n\n\nFor example, to validate a list of integers you might use something like the following:\n\n\nscores = serializers.ListField(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)\n\n\n\nThe \nListField\n class also supports a declarative style that allows you to write reusable list field classes.\n\n\nclass StringListField(serializers.ListField):\n child = serializers.CharField()\n\n\n\nWe can now reuse our custom \nStringListField\n class throughout our application, without having to provide a \nchild\n argument to it.\n\n\nDictField\n\n\nA field class that validates a dictionary of objects. The keys in \nDictField\n are always assumed to be string values.\n\n\nSignature\n: \nDictField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.\n\n\n\n\nFor example, to create a field that validates a mapping of strings to strings, you would write something like this:\n\n\ndocument = DictField(child=CharField())\n\n\n\nYou can also use the declarative style, as with \nListField\n. For example:\n\n\nclass DocumentField(DictField):\n child = CharField()\n\n\n\nJSONField\n\n\nA field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.\n\n\nSignature\n: \nJSONField(binary)\n\n\n\n\nbinary\n - If set to \nTrue\n then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to \nFalse\n.\n\n\n\n\n\n\nMiscellaneous fields\n\n\nReadOnlyField\n\n\nA field class that simply returns the value of the field without modification.\n\n\nThis field is used by default with \nModelSerializer\n when including field names that relate to an attribute rather than a model field.\n\n\nSignature\n: \nReadOnlyField()\n\n\nFor example, if \nhas_expired\n was a property on the \nAccount\n model, then the following serializer would automatically generate it as a \nReadOnlyField\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'has_expired')\n\n\n\nHiddenField\n\n\nA field class that does not take a value based on user input, but instead takes its value from a default value or callable.\n\n\nSignature\n: \nHiddenField()\n\n\nFor example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:\n\n\nmodified = serializers.HiddenField(default=timezone.now)\n\n\n\nThe \nHiddenField\n class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.\n\n\nFor further examples on \nHiddenField\n see the \nvalidators\n documentation.\n\n\nModelField\n\n\nA generic field that can be tied to any arbitrary model field. The \nModelField\n class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.\n\n\nThis field is used by \nModelSerializer\n to correspond to custom model field classes.\n\n\nSignature:\n \nModelField(model_field=\nDjango ModelField instance\n)\n\n\nThe \nModelField\n class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a \nModelField\n, it must be passed a field that is attached to an instantiated model. For example: \nModelField(model_field=MyModel()._meta.get_field('custom_field'))\n\n\nSerializerMethodField\n\n\nThis is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.\n\n\nSignature\n: \nSerializerMethodField(method_name=None)\n\n\n\n\nmethod_name\n - The name of the method on the serializer to be called. If not included this defaults to \nget_\nfield_name\n.\n\n\n\n\nThe serializer method referred to by the \nmethod_name\n argument should accept a single argument (in addition to \nself\n), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:\n\n\nfrom django.contrib.auth.models import User\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n days_since_joined = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n\n def get_days_since_joined(self, obj):\n return (now() - obj.date_joined).days\n\n\n\n\n\nCustom fields\n\n\nIf you want to create a custom field, you'll need to subclass \nField\n and then override either one or both of the \n.to_representation()\n and \n.to_internal_value()\n methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, \ndate\n/\ntime\n/\ndatetime\n or \nNone\n. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.\n\n\nThe \n.to_representation()\n method is called to convert the initial datatype into a primitive, serializable datatype.\n\n\nThe \nto_internal_value()\n method is called to restore a primitive datatype into its internal python representation. This method should raise a \nserializers.ValidationError\n if the data is invalid.\n\n\nNote that the \nWritableField\n class that was present in version 2.x no longer exists. You should subclass \nField\n and override \nto_internal_value()\n if the field supports data input.\n\n\nExamples\n\n\nLet's look at an example of serializing a class that represents an RGB color value:\n\n\nclass Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red \n= 0 and green \n= 0 and blue \n= 0)\n assert(red \n 256 and green \n 256 and blue \n 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, obj):\n return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue)\n\n\n\nBy default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override \n.get_attribute()\n and/or \n.get_value()\n.\n\n\nAs an example, let's create a field that can be used to represent the class name of the object being serialized:\n\n\nclass ClassNameField(serializers.Field):\n def get_attribute(self, obj):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return obj\n\n def to_representation(self, obj):\n \"\"\"\n Serialize the object's class name.\n \"\"\"\n return obj.__class__.__name__\n\n\n\nRaising validation errors\n\n\nOur \nColorField\n class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a \nserializers.ValidationError\n, like so:\n\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue)\n\n\n\nThe \n.fail()\n method is a shortcut for raising \nValidationError\n that takes a message string from the \nerror_messages\n dictionary. For example:\n\n\ndefault_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue)\n\n\n\nThis style keeps you error messages more cleanly separated from your code, and should be preferred.\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF Compound Fields\n\n\nThe \ndrf-compound-fields\n package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the \nmany=True\n option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.\n\n\nDRF Extra Fields\n\n\nThe \ndrf-extra-fields\n package provides extra serializer fields for REST framework, including \nBase64ImageField\n and \nPointField\n classes.\n\n\ndjangrestframework-recursive\n\n\nthe \ndjangorestframework-recursive\n package provides a \nRecursiveField\n for serializing and deserializing recursive structures\n\n\ndjango-rest-framework-gis\n\n\nThe \ndjango-rest-framework-gis\n package provides geographic addons for django rest framework like a \nGeometryField\n field and a GeoJSON serializer.\n\n\ndjango-rest-framework-hstore\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreField\n to support \ndjango-hstore\n \nDictionaryField\n model field.", + "text": "Serializer fields\n\n\n\n\nEach field in a Form class is responsible not only for validating data, but also for \"cleaning\" it \n normalizing it to a consistent format.\n\n\n \nDjango documentation\n\n\n\n\nSerializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.\n\n\n\n\nNote:\n The serializer fields are declared in \nfields.py\n, but by convention you should import them using \nfrom rest_framework import serializers\n and refer to fields as \nserializers.\nFieldName\n.\n\n\n\n\nCore arguments\n\n\nEach serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:\n\n\nread_only\n\n\nRead-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.\n\n\nSet this to \nTrue\n to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.\n\n\nDefaults to \nFalse\n\n\nwrite_only\n\n\nSet this to \nTrue\n to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.\n\n\nDefaults to \nFalse\n\n\nrequired\n\n\nNormally an error will be raised if a field is not supplied during deserialization.\nSet to false if this field is not required to be present during deserialization.\n\n\nSetting this to \nFalse\n also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.\n\n\nDefaults to \nTrue\n.\n\n\nallow_null\n\n\nNormally an error will be raised if \nNone\n is passed to a serializer field. Set this keyword argument to \nTrue\n if \nNone\n should be considered a valid value.\n\n\nDefaults to \nFalse\n\n\ndefault\n\n\nIf set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.\n\n\nThe \ndefault\n is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.\n\n\nMay be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a \nset_context\n method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for \nvalidators\n.\n\n\nWhen serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance.\n\n\nNote that setting a \ndefault\n value implies that the field is not required. Including both the \ndefault\n and \nrequired\n keyword arguments is invalid and will raise an error.\n\n\nsource\n\n\nThe name of the attribute that will be used to populate the field. May be a method that only takes a \nself\n argument, such as \nURLField(source='get_absolute_url')\n, or may use dotted notation to traverse attributes, such as \nEmailField(source='user.email')\n.\n\n\nThe value \nsource='*'\n has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.\n\n\nDefaults to the name of the field.\n\n\nvalidators\n\n\nA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise \nserializers.ValidationError\n, but Django's built-in \nValidationError\n is also supported for compatibility with validators defined in the Django codebase or third party Django packages.\n\n\nerror_messages\n\n\nA dictionary of error codes to error messages.\n\n\nlabel\n\n\nA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.\n\n\nhelp_text\n\n\nA text string that may be used as a description of the field in HTML form fields or other descriptive elements.\n\n\ninitial\n\n\nA value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as\nyou may do with any regular Django \nField\n:\n\n\nimport datetime\nfrom rest_framework import serializers\nclass ExampleSerializer(serializers.Serializer):\n day = serializers.DateField(initial=datetime.date.today)\n\n\n\nstyle\n\n\nA dictionary of key-value pairs that can be used to control how renderers should render the field.\n\n\nTwo examples here are \n'input_type'\n and \n'base_template'\n:\n\n\n# Use \ninput type=\"password\"\n for the input.\npassword = serializers.CharField(\n style={'input_type': 'password'}\n)\n\n# Use a radio input instead of a select input.\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'green', 'blue'],\n style={'base_template': 'radio.html'}\n)\n\n\n\nFor more details see the \nHTML \n Forms\n documentation.\n\n\n\n\nBoolean fields\n\n\nBooleanField\n\n\nA boolean representation.\n\n\nWhen using HTML encoded form input be aware that omitting a value will always be treated as setting a field to \nFalse\n, even if it has a \ndefault=True\n option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.\n\n\nCorresponds to \ndjango.db.models.fields.BooleanField\n.\n\n\nSignature:\n \nBooleanField()\n\n\nNullBooleanField\n\n\nA boolean representation that also accepts \nNone\n as a valid value.\n\n\nCorresponds to \ndjango.db.models.fields.NullBooleanField\n.\n\n\nSignature:\n \nNullBooleanField()\n\n\n\n\nString fields\n\n\nCharField\n\n\nA text representation. Optionally validates the text to be shorter than \nmax_length\n and longer than \nmin_length\n.\n\n\nCorresponds to \ndjango.db.models.fields.CharField\n or \ndjango.db.models.fields.TextField\n.\n\n\nSignature:\n \nCharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)\n\n\n\n\nmax_length\n - Validates that the input contains no more than this number of characters.\n\n\nmin_length\n - Validates that the input contains no fewer than this number of characters.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\ntrim_whitespace\n - If set to \nTrue\n then leading and trailing whitespace is trimmed. Defaults to \nTrue\n.\n\n\n\n\nThe \nallow_null\n option is also available for string fields, although its usage is discouraged in favor of \nallow_blank\n. It is valid to set both \nallow_blank=True\n and \nallow_null=True\n, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.\n\n\nEmailField\n\n\nA text representation, validates the text to be a valid e-mail address.\n\n\nCorresponds to \ndjango.db.models.fields.EmailField\n\n\nSignature:\n \nEmailField(max_length=None, min_length=None, allow_blank=False)\n\n\nRegexField\n\n\nA text representation, that validates the given value matches against a certain regular expression.\n\n\nCorresponds to \ndjango.forms.fields.RegexField\n.\n\n\nSignature:\n \nRegexField(regex, max_length=None, min_length=None, allow_blank=False)\n\n\nThe mandatory \nregex\n argument may either be a string, or a compiled python regular expression object.\n\n\nUses Django's \ndjango.core.validators.RegexValidator\n for validation.\n\n\nSlugField\n\n\nA \nRegexField\n that validates the input against the pattern \n[a-zA-Z0-9_-]+\n.\n\n\nCorresponds to \ndjango.db.models.fields.SlugField\n.\n\n\nSignature:\n \nSlugField(max_length=50, min_length=None, allow_blank=False)\n\n\nURLField\n\n\nA \nRegexField\n that validates the input against a URL matching pattern. Expects fully qualified URLs of the form \nhttp://\nhost\n/\npath\n.\n\n\nCorresponds to \ndjango.db.models.fields.URLField\n. Uses Django's \ndjango.core.validators.URLValidator\n for validation.\n\n\nSignature:\n \nURLField(max_length=200, min_length=None, allow_blank=False)\n\n\nUUIDField\n\n\nA field that ensures the input is a valid UUID string. The \nto_internal_value\n method will return a \nuuid.UUID\n instance. On output the field will return a string in the canonical hyphenated format, for example:\n\n\n\"de305d54-75b4-431b-adb2-eb6b9e546013\"\n\n\n\nSignature:\n \nUUIDField(format='hex_verbose')\n\n\n\n\nformat\n: Determines the representation format of the uuid value\n\n\n'hex_verbose'\n - The cannoncical hex representation, including hyphens: \n\"5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n\n'hex'\n - The compact hex representation of the UUID, not including hyphens: \n\"5ce0e9a55ffa654bcee01238041fb31a\"\n\n\n'int'\n - A 128 bit integer representation of the UUID: \n\"123456789012312313134124512351145145114\"\n\n\n'urn'\n - RFC 4122 URN representation of the UUID: \n\"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a\"\n\n Changing the \nformat\n parameters only affects representation values. All formats are accepted by \nto_internal_value\n\n\n\n\n\n\n\n\nFilePathField\n\n\nA field whose choices are limited to the filenames in a certain directory on the filesystem\n\n\nCorresponds to \ndjango.forms.fields.FilePathField\n.\n\n\nSignature:\n \nFilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)\n\n\n\n\npath\n - The absolute filesystem path to a directory from which this FilePathField should get its choice.\n\n\nmatch\n - A regular expression, as a string, that FilePathField will use to filter filenames.\n\n\nrecursive\n - Specifies whether all subdirectories of path should be included. Default is \nFalse\n.\n\n\nallow_files\n - Specifies whether files in the specified location should be included. Default is \nTrue\n. Either this or \nallow_folders\n must be \nTrue\n.\n\n\nallow_folders\n - Specifies whether folders in the specified location should be included. Default is \nFalse\n. Either this or \nallow_files\n must be \nTrue\n.\n\n\n\n\nIPAddressField\n\n\nA field that ensures the input is a valid IPv4 or IPv6 string.\n\n\nCorresponds to \ndjango.forms.fields.IPAddressField\n and \ndjango.forms.fields.GenericIPAddressField\n.\n\n\nSignature\n: \nIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\n\n\n\nprotocol\n Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.\n\n\nunpack_ipv4\n Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.\n\n\n\n\n\n\nNumeric fields\n\n\nIntegerField\n\n\nAn integer representation.\n\n\nCorresponds to \ndjango.db.models.fields.IntegerField\n, \ndjango.db.models.fields.SmallIntegerField\n, \ndjango.db.models.fields.PositiveIntegerField\n and \ndjango.db.models.fields.PositiveSmallIntegerField\n.\n\n\nSignature\n: \nIntegerField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nFloatField\n\n\nA floating point representation.\n\n\nCorresponds to \ndjango.db.models.fields.FloatField\n.\n\n\nSignature\n: \nFloatField(max_value=None, min_value=None)\n\n\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\n\n\nDecimalField\n\n\nA decimal representation, represented in Python by a \nDecimal\n instance.\n\n\nCorresponds to \ndjango.db.models.fields.DecimalField\n.\n\n\nSignature\n: \nDecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)\n\n\n\n\nmax_digits\n The maximum number of digits allowed in the number. It must be either \nNone\n or an integer greater than or equal to \ndecimal_places\n.\n\n\ndecimal_places\n The number of decimal places to store with the number.\n\n\ncoerce_to_string\n Set to \nTrue\n if string values should be returned for the representation, or \nFalse\n if \nDecimal\n objects should be returned. Defaults to the same value as the \nCOERCE_DECIMAL_TO_STRING\n settings key, which will be \nTrue\n unless overridden. If \nDecimal\n objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting \nlocalize\n will force the value to \nTrue\n.\n\n\nmax_value\n Validate that the number provided is no greater than this value.\n\n\nmin_value\n Validate that the number provided is no less than this value.\n\n\nlocalize\n Set to \nTrue\n to enable localization of input and output based on the current locale. This will also force \ncoerce_to_string\n to \nTrue\n. Defaults to \nFalse\n. Note that data formatting is enabled if you have set \nUSE_L10N=True\n in your settings file.\n\n\n\n\nExample usage\n\n\nTo validate numbers up to 999 with a resolution of 2 decimal places, you would use:\n\n\nserializers.DecimalField(max_digits=5, decimal_places=2)\n\n\n\nAnd to validate numbers up to anything less than one billion with a resolution of 10 decimal places:\n\n\nserializers.DecimalField(max_digits=19, decimal_places=10)\n\n\n\nThis field also takes an optional argument, \ncoerce_to_string\n. If set to \nTrue\n the representation will be output as a string. If set to \nFalse\n the representation will be left as a \nDecimal\n instance and the final representation will be determined by the renderer.\n\n\nIf unset, this will default to the same value as the \nCOERCE_DECIMAL_TO_STRING\n setting, which is \nTrue\n unless set otherwise.\n\n\n\n\nDate and time fields\n\n\nDateTimeField\n\n\nA date and time representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateTimeField\n.\n\n\nSignature:\n \nDateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATETIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndatetime\n objects should be returned by \nto_representation\n. In this case the datetime encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATETIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateTimeField\n format strings.\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style datetimes should be used. (eg \n'2013-01-29T12:34:56.000000Z'\n)\n\n\nWhen a value of \nNone\n is used for the format \ndatetime\n objects will be returned by \nto_representation\n and the final output representation will determined by the renderer class.\n\n\nauto_now_add\n model fields.\nauto_now\n and \n\n\nWhen using \nModelSerializer\n or \nHyperlinkedModelSerializer\n, note that any model fields with \nauto_now=True\n or \nauto_now_add=True\n will use serializer fields that are \nread_only=True\n by default.\n\n\nIf you want to override this behavior, you'll need to declare the \nDateTimeField\n explicitly on the serializer. For example:\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n created = serializers.DateTimeField()\n\n class Meta:\n model = Comment\n\n\n\nDateField\n\n\nA date representation.\n\n\nCorresponds to \ndjango.db.models.fields.DateField\n\n\nSignature:\n \nDateField(format=api_settings.DATE_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nDATE_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ndate\n objects should be returned by \nto_representation\n. In this case the date encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nDATE_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nDateField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style dates should be used. (eg \n'2013-01-29'\n)\n\n\nTimeField\n\n\nA time representation.\n\n\nCorresponds to \ndjango.db.models.fields.TimeField\n\n\nSignature:\n \nTimeField(format=api_settings.TIME_FORMAT, input_formats=None)\n\n\n\n\nformat\n - A string representing the output format. If not specified, this defaults to the same value as the \nTIME_FORMAT\n settings key, which will be \n'iso-8601'\n unless set. Setting to a format string indicates that \nto_representation\n return values should be coerced to string output. Format strings are described below. Setting this value to \nNone\n indicates that Python \ntime\n objects should be returned by \nto_representation\n. In this case the time encoding will be determined by the renderer.\n\n\ninput_formats\n - A list of strings representing the input formats which may be used to parse the date. If not specified, the \nTIME_INPUT_FORMATS\n setting will be used, which defaults to \n['iso-8601']\n.\n\n\n\n\nTimeField\n format strings\n\n\nFormat strings may either be \nPython strftime formats\n which explicitly specify the format, or the special string \n'iso-8601'\n, which indicates that \nISO 8601\n style times should be used. (eg \n'12:34:56.000000'\n)\n\n\nDurationField\n\n\nA Duration representation.\nCorresponds to \ndjango.db.models.fields.DurationField\n\n\nThe \nvalidated_data\n for these fields will contain a \ndatetime.timedelta\n instance.\nThe representation is a string following this format \n'[DD] [HH:[MM:]]ss[.uuuuuu]'\n.\n\n\nNote:\n This field is only available with Django versions \n= 1.8.\n\n\nSignature:\n \nDurationField()\n\n\n\n\nChoice selection fields\n\n\nChoiceField\n\n\nA field that can accept a value out of a limited set of choices.\n\n\nUsed by \nModelSerializer\n to automatically generate fields if the corresponding model field includes a \nchoices=\u2026\n argument.\n\n\nSignature:\n \nChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nBoth the \nallow_blank\n and \nallow_null\n are valid options on \nChoiceField\n, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\nMultipleChoiceField\n\n\nA field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. \nto_internal_value\n returns a \nset\n containing the selected values.\n\n\nSignature:\n \nMultipleChoiceField(choices)\n\n\n\n\nchoices\n - A list of valid values, or a list of \n(key, display_name)\n tuples.\n\n\nallow_blank\n - If set to \nTrue\n then the empty string should be considered a valid value. If set to \nFalse\n then the empty string is considered invalid and will raise a validation error. Defaults to \nFalse\n.\n\n\nhtml_cutoff\n - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to \nNone\n.\n\n\nhtml_cutoff_text\n - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to \n\"More than {count} items\u2026\"\n\n\n\n\nAs with \nChoiceField\n, both the \nallow_blank\n and \nallow_null\n options are valid, although it is highly recommended that you only use one and not both. \nallow_blank\n should be preferred for textual choices, and \nallow_null\n should be preferred for numeric or other non-textual choices.\n\n\n\n\nFile upload fields\n\n\nParsers and file uploads.\n\n\nThe \nFileField\n and \nImageField\n classes are only suitable for use with \nMultiPartParser\n or \nFileUploadParser\n. Most parsers, such as e.g. JSON don't support file uploads.\nDjango's regular \nFILE_UPLOAD_HANDLERS\n are used for handling uploaded files.\n\n\nFileField\n\n\nA file representation. Performs Django's standard FileField validation.\n\n\nCorresponds to \ndjango.forms.fields.FileField\n.\n\n\nSignature:\n \nFileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nImageField\n\n\nAn image representation. Validates the uploaded file content as matching a known image format.\n\n\nCorresponds to \ndjango.forms.fields.ImageField\n.\n\n\nSignature:\n \nImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)\n\n\n\n\nmax_length\n - Designates the maximum length for the file name.\n\n\nallow_empty_file\n - Designates if empty files are allowed.\n\n\nuse_url\n - If set to \nTrue\n then URL string values will be used for the output representation. If set to \nFalse\n then filename string values will be used for the output representation. Defaults to the value of the \nUPLOADED_FILES_USE_URL\n settings key, which is \nTrue\n unless set otherwise.\n\n\n\n\nRequires either the \nPillow\n package or \nPIL\n package. The \nPillow\n package is recommended, as \nPIL\n is no longer actively maintained.\n\n\n\n\nComposite fields\n\n\nListField\n\n\nA field class that validates a list of objects.\n\n\nSignature\n: \nListField(child, min_length=None, max_length=None)\n\n\n\n\nchild\n - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.\n\n\nmin_length\n - Validates that the list contains no fewer than this number of elements.\n\n\nmax_length\n - Validates that the list contains no more than this number of elements.\n\n\n\n\nFor example, to validate a list of integers you might use something like the following:\n\n\nscores = serializers.ListField(\n child=serializers.IntegerField(min_value=0, max_value=100)\n)\n\n\n\nThe \nListField\n class also supports a declarative style that allows you to write reusable list field classes.\n\n\nclass StringListField(serializers.ListField):\n child = serializers.CharField()\n\n\n\nWe can now reuse our custom \nStringListField\n class throughout our application, without having to provide a \nchild\n argument to it.\n\n\nDictField\n\n\nA field class that validates a dictionary of objects. The keys in \nDictField\n are always assumed to be string values.\n\n\nSignature\n: \nDictField(child)\n\n\n\n\nchild\n - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.\n\n\n\n\nFor example, to create a field that validates a mapping of strings to strings, you would write something like this:\n\n\ndocument = DictField(child=CharField())\n\n\n\nYou can also use the declarative style, as with \nListField\n. For example:\n\n\nclass DocumentField(DictField):\n child = CharField()\n\n\n\nJSONField\n\n\nA field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.\n\n\nSignature\n: \nJSONField(binary)\n\n\n\n\nbinary\n - If set to \nTrue\n then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to \nFalse\n.\n\n\n\n\n\n\nMiscellaneous fields\n\n\nReadOnlyField\n\n\nA field class that simply returns the value of the field without modification.\n\n\nThis field is used by default with \nModelSerializer\n when including field names that relate to an attribute rather than a model field.\n\n\nSignature\n: \nReadOnlyField()\n\n\nFor example, if \nhas_expired\n was a property on the \nAccount\n model, then the following serializer would automatically generate it as a \nReadOnlyField\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = Account\n fields = ('id', 'account_name', 'has_expired')\n\n\n\nHiddenField\n\n\nA field class that does not take a value based on user input, but instead takes its value from a default value or callable.\n\n\nSignature\n: \nHiddenField()\n\n\nFor example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:\n\n\nmodified = serializers.HiddenField(default=timezone.now)\n\n\n\nThe \nHiddenField\n class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.\n\n\nFor further examples on \nHiddenField\n see the \nvalidators\n documentation.\n\n\nModelField\n\n\nA generic field that can be tied to any arbitrary model field. The \nModelField\n class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.\n\n\nThis field is used by \nModelSerializer\n to correspond to custom model field classes.\n\n\nSignature:\n \nModelField(model_field=\nDjango ModelField instance\n)\n\n\nThe \nModelField\n class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a \nModelField\n, it must be passed a field that is attached to an instantiated model. For example: \nModelField(model_field=MyModel()._meta.get_field('custom_field'))\n\n\nSerializerMethodField\n\n\nThis is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.\n\n\nSignature\n: \nSerializerMethodField(method_name=None)\n\n\n\n\nmethod_name\n - The name of the method on the serializer to be called. If not included this defaults to \nget_\nfield_name\n.\n\n\n\n\nThe serializer method referred to by the \nmethod_name\n argument should accept a single argument (in addition to \nself\n), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:\n\n\nfrom django.contrib.auth.models import User\nfrom django.utils.timezone import now\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.ModelSerializer):\n days_since_joined = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n\n def get_days_since_joined(self, obj):\n return (now() - obj.date_joined).days\n\n\n\n\n\nCustom fields\n\n\nIf you want to create a custom field, you'll need to subclass \nField\n and then override either one or both of the \n.to_representation()\n and \n.to_internal_value()\n methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, \ndate\n/\ntime\n/\ndatetime\n or \nNone\n. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.\n\n\nThe \n.to_representation()\n method is called to convert the initial datatype into a primitive, serializable datatype.\n\n\nThe \nto_internal_value()\n method is called to restore a primitive datatype into its internal python representation. This method should raise a \nserializers.ValidationError\n if the data is invalid.\n\n\nNote that the \nWritableField\n class that was present in version 2.x no longer exists. You should subclass \nField\n and override \nto_internal_value()\n if the field supports data input.\n\n\nExamples\n\n\nLet's look at an example of serializing a class that represents an RGB color value:\n\n\nclass Color(object):\n \"\"\"\n A color represented in the RGB colorspace.\n \"\"\"\n def __init__(self, red, green, blue):\n assert(red \n= 0 and green \n= 0 and blue \n= 0)\n assert(red \n 256 and green \n 256 and blue \n 256)\n self.red, self.green, self.blue = red, green, blue\n\nclass ColorField(serializers.Field):\n \"\"\"\n Color objects are serialized into 'rgb(#, #, #)' notation.\n \"\"\"\n def to_representation(self, obj):\n return \"rgb(%d, %d, %d)\" % (obj.red, obj.green, obj.blue)\n\n def to_internal_value(self, data):\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n return Color(red, green, blue)\n\n\n\nBy default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override \n.get_attribute()\n and/or \n.get_value()\n.\n\n\nAs an example, let's create a field that can be used to represent the class name of the object being serialized:\n\n\nclass ClassNameField(serializers.Field):\n def get_attribute(self, obj):\n # We pass the object instance onto `to_representation`,\n # not just the field attribute.\n return obj\n\n def to_representation(self, obj):\n \"\"\"\n Serialize the object's class name.\n \"\"\"\n return obj.__class__.__name__\n\n\n\nRaising validation errors\n\n\nOur \nColorField\n class above currently does not perform any data validation.\nTo indicate invalid data, we should raise a \nserializers.ValidationError\n, like so:\n\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n msg = 'Incorrect type. Expected a string, but got %s'\n raise ValidationError(msg % type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n raise ValidationError('Value out of range. Must be between 0 and 255.')\n\n return Color(red, green, blue)\n\n\n\nThe \n.fail()\n method is a shortcut for raising \nValidationError\n that takes a message string from the \nerror_messages\n dictionary. For example:\n\n\ndefault_error_messages = {\n 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',\n 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',\n 'out_of_range': 'Value out of range. Must be between 0 and 255.'\n}\n\ndef to_internal_value(self, data):\n if not isinstance(data, six.text_type):\n self.fail('incorrect_type', input_type=type(data).__name__)\n\n if not re.match(r'^rgb\\([0-9]+,[0-9]+,[0-9]+\\)$', data):\n self.fail('incorrect_format')\n\n data = data.strip('rgb(').rstrip(')')\n red, green, blue = [int(col) for col in data.split(',')]\n\n if any([col \n 255 or col \n 0 for col in (red, green, blue)]):\n self.fail('out_of_range')\n\n return Color(red, green, blue)\n\n\n\nThis style keeps you error messages more cleanly separated from your code, and should be preferred.\n\n\nThird party packages\n\n\nThe following third party packages are also available.\n\n\nDRF Compound Fields\n\n\nThe \ndrf-compound-fields\n package provides \"compound\" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the \nmany=True\n option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.\n\n\nDRF Extra Fields\n\n\nThe \ndrf-extra-fields\n package provides extra serializer fields for REST framework, including \nBase64ImageField\n and \nPointField\n classes.\n\n\ndjangrestframework-recursive\n\n\nthe \ndjangorestframework-recursive\n package provides a \nRecursiveField\n for serializing and deserializing recursive structures\n\n\ndjango-rest-framework-gis\n\n\nThe \ndjango-rest-framework-gis\n package provides geographic addons for django rest framework like a \nGeometryField\n field and a GeoJSON serializer.\n\n\ndjango-rest-framework-hstore\n\n\nThe \ndjango-rest-framework-hstore\n package provides an \nHStoreField\n to support \ndjango-hstore\n \nDictionaryField\n model field.", "title": "Serializer fields" }, { @@ -1772,7 +1772,7 @@ }, { "location": "/api-guide/fields/#default", - "text": "If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a set_context method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for validators . Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.", + "text": "If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. The default is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a set_context method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for validators . When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance. Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.", "title": "default" }, { @@ -3907,18 +3907,33 @@ }, { "location": "/topics/documenting-your-api/", - "text": "Documenting your API\n\n\n\n\nA REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state.\n\n\n Roy Fielding, \nREST APIs must be hypertext driven\n\n\n\n\nThere are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.\n\n\nEndpoint documentation\n\n\nThe most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.\n\n\n\n\nDRF Docs\n\n\nDRF Docs\n allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the \nwebsite\n while there is also a \ndemo\n available for people to see what it looks like. \nLive API Endpoints\n allow you to utilize the endpoints from within the documentation in a neat way.\n\n\nFeatures include customizing the template with your branding, settings for hiding the docs depending on the environment and more.\n\n\nBoth this package and Django REST Swagger are fully documented, well supported, and come highly recommended.\n\n\n\n\n\n\nDjango REST Swagger\n\n\nMarc Gibbons' \nDjango REST Swagger\n integrates REST framework with the \nSwagger\n API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.\n\n\nDjango REST Swagger supports REST framework versions 2.3 and above.\n\n\nMark is also the author of the \nREST Framework Docs\n package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger.\n\n\nBoth this package and DRF docs are fully documented, well supported, and come highly recommended.\n\n\n\n\n\n\nDRF AutoDocs\n\n\nOleksander Mashianovs' \nDRF Auto Docs\n automated api renderer.\n\n\nCollects almost all the code you written into documentation effortlessly.\n\n\nSupports:\n\n\n\n\nfunctional view docs\n\n\ntree-like structure\n\n\nDocstrings:\n\n\nmarkdown\n\n\npreserve space \n newlines\n\n\nformatting with nice syntax\n\n\nFields:\n\n\nchoices rendering\n\n\nhelp_text (to specify SerializerMethodField output, etc)\n\n\nsmart read_only/required rendering\n\n\nEndpoint properties:\n\n\nfilter_backends\n\n\nauthentication_classes\n\n\npermission_classes\n\n\nextra url params(GET params)\n\n\n\n\n\n\n\n\nApiary\n\n\nThere are various other online tools and services for providing API documentation. One notable service is \nApiary\n. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing \n prototyping, and various other tools.\n\n\n\n\n\n\nSelf describing APIs\n\n\nThe browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.\n\n\n\n\n\n\nSetting the title\n\n\nThe title that is used in the browsable API is generated from the view class name or function name. Any trailing \nView\n or \nViewSet\n suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.\n\n\nFor example, the view \nUserListView\n, will be named \nUser List\n when presented in the browsable API.\n\n\nWhen working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set \nUserViewSet\n will generate views named \nUser List\n and \nUser Instance\n.\n\n\nSetting the description\n\n\nThe description in the browsable API is generated from the docstring of the view or viewset.\n\n\nIf the python \nmarkdown\n library is installed, then \nmarkdown syntax\n may be used in the docstring, and will be converted to HTML in the browsable API. For example:\n\n\nclass AccountListView(views.APIView):\n \"\"\"\n Returns a list of all **active** accounts in the system.\n\n For more details on how accounts are activated please [see here][ref].\n\n [ref]: http://example.com/activating-accounts\n \"\"\"\n\n\n\nNote that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the the list and retrieve views, use docstring sections as described in \nSchemas as documentation: Examples\n.\n\n\nThe \nOPTIONS\n method\n\n\nREST framework APIs also support programmatically accessible descriptions, using the \nOPTIONS\n HTTP method. A view will respond to an \nOPTIONS\n request with metadata including the name, description, and the various media types it accepts and responds with.\n\n\nWhen using the generic views, any \nOPTIONS\n requests will additionally respond with metadata regarding any \nPOST\n or \nPUT\n actions available, describing which fields are on the serializer.\n\n\nYou can modify the response behavior to \nOPTIONS\n requests by overriding the \nmetadata\n view method. For example:\n\n\ndef metadata(self, request):\n \"\"\"\n Don't include the view description in OPTIONS responses.\n \"\"\"\n data = super(ExampleView, self).metadata(request)\n data.pop('description')\n return data\n\n\n\n\n\nThe hypermedia approach\n\n\nTo be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.\n\n\nIn this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the \nmedia types\n that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.\n\n\nTo implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The \nREST, Hypermedia \n HATEOAS\n section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.", + "text": "Documenting your API\n\n\n\n\nA REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state.\n\n\n Roy Fielding, \nREST APIs must be hypertext driven\n\n\n\n\nREST framework provides built-in support for API documentation. There are also a number of great third-party documentation tools available.\n\n\nBuilt-in API documentation\n\n\nThe built-in API documentation includes:\n\n\n\n\nDocumentation of API endpoints.\n\n\nAutomatically generated code samples for each of the available API client libraries.\n\n\nSupport for API interaction.\n\n\n\n\nInstallation\n\n\nThe \ncoreapi\n library is required as a dependancy for the API docs. Make sure\nto install the latest version. The \npygments\n and \nmarkdown\n libraries\nare optional but recommended.\n\n\nTo install the API documentation, you'll need to include it in your projects URLconf:\n\n\nfrom rest_framework.documentation import include_docs_urls\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title='My API title'))\n]\n\n\n\nThis will include two different views:\n\n\n\n\n/docs/\n - The documentation page itself.\n\n\n/docs/schema.js\n - A JavaScript resource that exposes the API schema.\n\n\n\n\nDocumenting your views\n\n\nYou can document your views by including docstrings that describe each of the available actions.\nFor example:\n\n\nclass UserList(generics.ListAPIView):\n \"\"\"\n Return a list of all the existing users.\n \"\"\"\"\n\n\n\nIf a view supports multiple methods, you should split your documentation using \nmethod:\n style delimiters.\n\n\nclass UserList(generics.ListCreateAPIView):\n \"\"\"\n get:\n Return a list of all the existing users.\n\n post:\n Create a new user instance.\n \"\"\"\n\n\n\nWhen using viewsets, you should use the relevant action names as delimiters.\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n retrieve:\n Return the given user.\n\n list:\n Return a list of all the existing users.\n\n create:\n Create a new user instance.\n \"\"\"\n\n\n\n\n\nThird party packages\n\n\nThere are a number of mature third-party packages for providing API documentation.\n\n\nDRF Docs\n\n\nDRF Docs\n allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the \nwebsite\n while there is also a \ndemo\n available for people to see what it looks like. \nLive API Endpoints\n allow you to utilize the endpoints from within the documentation in a neat way.\n\n\nFeatures include customizing the template with your branding, settings for hiding the docs depending on the environment and more.\n\n\nBoth this package and Django REST Swagger are fully documented, well supported, and come highly recommended.\n\n\n\n\n\n\nDjango REST Swagger\n\n\nMarc Gibbons' \nDjango REST Swagger\n integrates REST framework with the \nSwagger\n API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.\n\n\nDjango REST Swagger supports REST framework versions 2.3 and above.\n\n\nMark is also the author of the \nREST Framework Docs\n package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger.\n\n\nBoth this package and DRF docs are fully documented, well supported, and come highly recommended.\n\n\n\n\n\n\nDRF AutoDocs\n\n\nOleksander Mashianovs' \nDRF Auto Docs\n automated api renderer.\n\n\nCollects almost all the code you written into documentation effortlessly.\n\n\nSupports:\n\n\n\n\nfunctional view docs\n\n\ntree-like structure\n\n\nDocstrings:\n\n\nmarkdown\n\n\npreserve space \n newlines\n\n\nformatting with nice syntax\n\n\nFields:\n\n\nchoices rendering\n\n\nhelp_text (to specify SerializerMethodField output, etc)\n\n\nsmart read_only/required rendering\n\n\nEndpoint properties:\n\n\nfilter_backends\n\n\nauthentication_classes\n\n\npermission_classes\n\n\nextra url params(GET params)\n\n\n\n\n\n\n\n\nApiary\n\n\nThere are various other online tools and services for providing API documentation. One notable service is \nApiary\n. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing \n prototyping, and various other tools.\n\n\n\n\n\n\nSelf describing APIs\n\n\nThe browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.\n\n\n\n\n\n\nSetting the title\n\n\nThe title that is used in the browsable API is generated from the view class name or function name. Any trailing \nView\n or \nViewSet\n suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.\n\n\nFor example, the view \nUserListView\n, will be named \nUser List\n when presented in the browsable API.\n\n\nWhen working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set \nUserViewSet\n will generate views named \nUser List\n and \nUser Instance\n.\n\n\nSetting the description\n\n\nThe description in the browsable API is generated from the docstring of the view or viewset.\n\n\nIf the python \nmarkdown\n library is installed, then \nmarkdown syntax\n may be used in the docstring, and will be converted to HTML in the browsable API. For example:\n\n\nclass AccountListView(views.APIView):\n \"\"\"\n Returns a list of all **active** accounts in the system.\n\n For more details on how accounts are activated please [see here][ref].\n\n [ref]: http://example.com/activating-accounts\n \"\"\"\n\n\n\nNote that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the the list and retrieve views, use docstring sections as described in \nSchemas as documentation: Examples\n.\n\n\nThe \nOPTIONS\n method\n\n\nREST framework APIs also support programmatically accessible descriptions, using the \nOPTIONS\n HTTP method. A view will respond to an \nOPTIONS\n request with metadata including the name, description, and the various media types it accepts and responds with.\n\n\nWhen using the generic views, any \nOPTIONS\n requests will additionally respond with metadata regarding any \nPOST\n or \nPUT\n actions available, describing which fields are on the serializer.\n\n\nYou can modify the response behavior to \nOPTIONS\n requests by overriding the \nmetadata\n view method. For example:\n\n\ndef metadata(self, request):\n \"\"\"\n Don't include the view description in OPTIONS responses.\n \"\"\"\n data = super(ExampleView, self).metadata(request)\n data.pop('description')\n return data\n\n\n\n\n\nThe hypermedia approach\n\n\nTo be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.\n\n\nIn this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the \nmedia types\n that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.\n\n\nTo implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The \nREST, Hypermedia \n HATEOAS\n section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.", "title": "Documenting your API" }, { "location": "/topics/documenting-your-api/#documenting-your-api", - "text": "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state. Roy Fielding, REST APIs must be hypertext driven There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints.", + "text": "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state. Roy Fielding, REST APIs must be hypertext driven REST framework provides built-in support for API documentation. There are also a number of great third-party documentation tools available.", "title": "Documenting your API" }, { - "location": "/topics/documenting-your-api/#endpoint-documentation", - "text": "The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way.", - "title": "Endpoint documentation" + "location": "/topics/documenting-your-api/#built-in-api-documentation", + "text": "The built-in API documentation includes: Documentation of API endpoints. Automatically generated code samples for each of the available API client libraries. Support for API interaction.", + "title": "Built-in API documentation" + }, + { + "location": "/topics/documenting-your-api/#installation", + "text": "The coreapi library is required as a dependancy for the API docs. Make sure\nto install the latest version. The pygments and markdown libraries\nare optional but recommended. To install the API documentation, you'll need to include it in your projects URLconf: from rest_framework.documentation import include_docs_urls\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title='My API title'))\n] This will include two different views: /docs/ - The documentation page itself. /docs/schema.js - A JavaScript resource that exposes the API schema.", + "title": "Installation" + }, + { + "location": "/topics/documenting-your-api/#documenting-your-views", + "text": "You can document your views by including docstrings that describe each of the available actions.\nFor example: class UserList(generics.ListAPIView):\n \"\"\"\n Return a list of all the existing users.\n \"\"\"\" If a view supports multiple methods, you should split your documentation using method: style delimiters. class UserList(generics.ListCreateAPIView):\n \"\"\"\n get:\n Return a list of all the existing users.\n\n post:\n Create a new user instance.\n \"\"\" When using viewsets, you should use the relevant action names as delimiters. class UserViewSet(viewsets.ModelViewSet):\n \"\"\"\n retrieve:\n Return the given user.\n\n list:\n Return a list of all the existing users.\n\n create:\n Create a new user instance.\n \"\"\"", + "title": "Documenting your views" + }, + { + "location": "/topics/documenting-your-api/#third-party-packages", + "text": "There are a number of mature third-party packages for providing API documentation.", + "title": "Third party packages" }, { "location": "/topics/documenting-your-api/#drf-docs", @@ -3967,7 +3982,7 @@ }, { "location": "/topics/api-clients/", - "text": "API Clients\n\n\nAn API client handles the underlying details of how network requests are made\nand how responses are decoded. They present the developer with an application\ninterface to work against, rather than working directly with the network interface.\n\n\nThe API clients documented here are not restricted to APIs built with Django REST framework.\n They can be used with any API that exposes a supported schema format.\n\n\nFor example, \nthe Heroku platform API\n exposes a schema in the JSON\nHyperschema format. As a result, the Core API command line client and Python\nclient library can be \nused to interact with the Heroku API\n.\n\n\nClient-side Core API\n\n\nCore API\n is a document specification that can be used to describe APIs. It can\nbe used either server-side, as is done with REST framework's \nschema generation\n,\nor used client-side, as described here.\n\n\nWhen used client-side, Core API allows for \ndynamically driven client libraries\n\nthat can interact with any API that exposes a supported schema or hypermedia\nformat.\n\n\nUsing a dynamically driven client has a number of advantages over interacting\nwith an API by building HTTP requests directly.\n\n\nMore meaningful interaction\n\n\nAPI interactions are presented in a more meaningful way. You're working at\nthe application interface layer, rather than the network interface layer.\n\n\nResilience \n evolvability\n\n\nThe client determines what endpoints are available, what parameters exist\nagainst each particular endpoint, and how HTTP requests are formed.\n\n\nThis also allows for a degree of API evolvability. URLs can be modified\nwithout breaking existing clients, or more efficient encodings can be used\non-the-wire, with clients transparently upgrading.\n\n\nSelf-descriptive APIs\n\n\nA dynamically driven client is able to present documentation on the API to the\nend user. This documentation allows the user to discover the available endpoints\nand parameters, and better understand the API they are working with.\n\n\nBecause this documentation is driven by the API schema it will always be fully\nup to date with the most recently deployed version of the service.\n\n\n\n\nCommand line client\n\n\nThe command line client allows you to inspect and interact with any API that\nexposes a supported schema format.\n\n\nGetting started\n\n\nTo install the Core API command line client, use \npip\n.\n\n\nNote that the command-line client is a separate package to the\npython client library. Make sure to install \ncoreapi-cli\n.\n\n\n$ pip install coreapi-cli\n\n\n\nTo start inspecting and interacting with an API the schema must first be loaded\nfrom the network.\n\n\n$ coreapi get http://api.example.org/\n\nPastebin API \"http://127.0.0.1:8000/\"\n\nsnippets: {\n create(code, [title], [linenos], [language], [style])\n destroy(pk)\n highlight(pk)\n list([page])\n partial_update(pk, [title], [code], [linenos], [language], [style])\n retrieve(pk)\n update(pk, code, [title], [linenos], [language], [style])\n}\nusers: {\n list([page])\n retrieve(pk)\n}\n\n\n\nThis will then load the schema, displaying the resulting \nDocument\n. This\n\nDocument\n includes all the available interactions that may be made against the API.\n\n\nTo interact with the API, use the \naction\n command. This command requires a list\nof keys that are used to index into the link.\n\n\n$ coreapi action users list\n[\n {\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"id\": 2,\n \"username\": \"aziz\",\n \"snippets\": []\n },\n ...\n]\n\n\n\nTo inspect the underlying HTTP request and response, use the \n--debug\n flag.\n\n\n$ coreapi action users list --debug\n\n GET /users/ HTTP/1.1\n\n Accept: application/vnd.coreapi+json, */*\n\n Authorization: Basic bWF4Om1heA==\n\n Host: 127.0.0.1\n\n User-Agent: coreapi\n\n 200 OK\n\n Allow: GET, HEAD, OPTIONS\n\n Content-Type: application/json\n\n Date: Thu, 30 Jun 2016 10:51:46 GMT\n\n Server: WSGIServer/0.1 Python/2.7.10\n\n Vary: Accept, Cookie\n\n\n\n [{\"url\":\"http://127.0.0.1/users/2/\",\"id\":2,\"username\":\"aziz\",\"snippets\":[]},{\"url\":\"http://127.0.0.1/users/3/\",\"id\":3,\"username\":\"amy\",\"snippets\":[\"http://127.0.0.1/snippets/3/\"]},{\"url\":\"http://127.0.0.1/users/4/\",\"id\":4,\"username\":\"max\",\"snippets\":[\"http://127.0.0.1/snippets/4/\",\"http://127.0.0.1/snippets/5/\",\"http://127.0.0.1/snippets/6/\",\"http://127.0.0.1/snippets/7/\"]},{\"url\":\"http://127.0.0.1/users/5/\",\"id\":5,\"username\":\"jose\",\"snippets\":[]},{\"url\":\"http://127.0.0.1/users/6/\",\"id\":6,\"username\":\"admin\",\"snippets\":[\"http://127.0.0.1/snippets/1/\",\"http://127.0.0.1/snippets/2/\"]}]\n\n[\n ...\n]\n\n\n\nSome actions may include optional or required parameters.\n\n\n$ coreapi action users create --param username=example\n\n\n\nWhen using \n--param\n, the type of the input will be determined automatically.\n\n\nIf you want to be more explicit about the parameter type then use \n--data\n for\nany null, numeric, boolean, list, or object inputs, and use \n--string\n for string inputs.\n\n\n$ coreapi action users edit --string username=tomchristie --data is_admin=true\n\n\n\nAuthentication \n headers\n\n\nThe \ncredentials\n command is used to manage the request \nAuthentication:\n header.\nAny credentials added are always linked to a particular domain, so as to ensure\nthat credentials are not leaked across differing APIs.\n\n\nThe format for adding a new credential is:\n\n\n$ coreapi credentials add \ndomain\n \ncredentials string\n\n\n\n\nFor instance:\n\n\n$ coreapi credentials add api.example.org \"Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\"\n\n\n\nThe optional \n--auth\n flag also allows you to add specific types of authentication,\nhandling the encoding for you. Currently only \n\"basic\"\n is supported as an option here.\nFor example:\n\n\n$ coreapi credentials add api.example.org tomchristie:foobar --auth basic\n\n\n\nYou can also add specific request headers, using the \nheaders\n command:\n\n\n$ coreapi headers add api.example.org x-api-version 2\n\n\n\nFor more information and a listing of the available subcommands use \ncoreapi\ncredentials --help\n or \ncoreapi headers --help\n.\n\n\nCodecs\n\n\nBy default the command line client only includes support for reading Core JSON\nschemas, however it includes a plugin system for installing additional codecs.\n\n\n$ pip install openapi-codec jsonhyperschema-codec hal-codec\n$ coreapi codecs show\nCodecs\ncorejson application/vnd.coreapi+json encoding, decoding\nhal application/hal+json encoding, decoding\nopenapi application/openapi+json encoding, decoding\njsonhyperschema application/schema+json decoding\njson application/json data\ntext text/* data\n\n\n\nUtilities\n\n\nThe command line client includes functionality for bookmarking API URLs\nunder a memorable name. For example, you can add a bookmark for the\nexisting API, like so...\n\n\n$ coreapi bookmarks add accountmanagement\n\n\n\nThere is also functionality for navigating forward or backward through the\nhistory of which API URLs have been accessed.\n\n\n$ coreapi history show\n$ coreapi history back\n\n\n\nFor more information and a listing of the available subcommands use\n\ncoreapi bookmarks --help\n or \ncoreapi history --help\n.\n\n\nOther commands\n\n\nTo display the current \nDocument\n:\n\n\n$ coreapi show\n\n\n\nTo reload the current \nDocument\n from the network:\n\n\n$ coreapi reload\n\n\n\nTo load a schema file from disk:\n\n\n$ coreapi load my-api-schema.json --format corejson\n\n\n\nTo dump the current document to console in a given format:\n\n\n$ coreapi dump --format openapi\n\n\n\nTo remove the current document, along with all currently saved history,\ncredentials, headers and bookmarks:\n\n\n$ coreapi clear\n\n\n\n\n\nPython client library\n\n\nThe \ncoreapi\n Python package allows you to programmatically interact with any\nAPI that exposes a supported schema format.\n\n\nGetting started\n\n\nYou'll need to install the \ncoreapi\n package using \npip\n before you can get\nstarted.\n\n\n$ pip install coreapi\n\n\n\nIn order to start working with an API, we first need a \nClient\n instance. The\nclient holds any configuration around which codecs and transports are supported\nwhen interacting with an API, which allows you to provide for more advanced\nkinds of behaviour.\n\n\nimport coreapi\nclient = coreapi.Client()\n\n\n\nOnce we have a \nClient\n instance, we can fetch an API schema from the network.\n\n\nschema = client.get('https://api.example.org/')\n\n\n\nThe object returned from this call will be a \nDocument\n instance, which is\nthe internal representation of the interface that we are interacting with.\n\n\nNow that we have our schema \nDocument\n, we can now start to interact with the API:\n\n\nusers = client.action(schema, ['users', 'list'])\n\n\n\nSome endpoints may include named parameters, which might be either optional or required:\n\n\nnew_user = client.action(schema, ['users', 'create'], params={\"username\": \"max\"})\n\n\n\nCodecs\n\n\nCodecs are responsible for encoding or decoding Documents.\n\n\nThe decoding process is used by a client to take a bytestring of an API schema\ndefinition, and returning the Core API \nDocument\n that represents that interface.\n\n\nA codec should be associated with a particular media type, such as \n'application/coreapi+json'\n.\n\n\nThis media type is used by the server in the response \nContent-Type\n header,\nin order to indicate what kind of data is being returned in the response.\n\n\nConfiguring codecs\n\n\nThe codecs that are available can be configured when instantiating a client.\nThe keyword argument used here is \ndecoders\n, because in the context of a\nclient the codecs are only for \ndecoding\n responses.\n\n\nIn the following example we'll configure a client to only accept \nCore JSON\n\nand \nJSON\n responses. This will allow us to receive and decode a Core JSON schema,\nand subsequently to receive JSON responses made against the API.\n\n\nfrom coreapi import codecs, Client\n\ndecoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()]\nclient = Client(decoders=decoders)\n\n\n\nLoading and saving schemas\n\n\nYou can use a codec directly, in order to load an existing schema definition,\nand return the resulting \nDocument\n.\n\n\ninput_file = open('my-api-schema.json', 'rb')\nschema_definition = input_file.read()\ncodec = codecs.CoreJSONCodec()\nschema = codec.load(schema_definition)\n\n\n\nYou can also use a codec directly to generate a schema definition given a \nDocument\n instance:\n\n\nschema_definition = codec.dump(schema)\noutput_file = open('my-api-schema.json', 'rb')\noutput_file.write(schema_definition)\n\n\n\nTransports\n\n\nTransports are responsible for making network requests. The set of transports\nthat a client has installed determines which network protocols it is able to\nsupport.\n\n\nCurrently the \ncoreapi\n library only includes an HTTP/HTTPS transport, but\nother protocols can also be supported.\n\n\nConfiguring transports\n\n\nThe behaviour of the network layer can be customized by configuring the\ntransports that the client is instantiated with.\n\n\nimport requests\nfrom coreapi import transports, Client\n\ncredentials = {'api.example.org': 'Token 3bd44a009d16ff'}\ntransports = transports.HTTPTransport(credentials=credentials)\nclient = Client(transports=transports)\n\n\n\nMore complex customizations can also be achieved, for example modifying the\nunderlying \nrequests.Session\n instance to \nattach transport adaptors\n\nthat modify the outgoing requests.", + "text": "API Clients\n\n\nAn API client handles the underlying details of how network requests are made\nand how responses are decoded. They present the developer with an application\ninterface to work against, rather than working directly with the network interface.\n\n\nThe API clients documented here are not restricted to APIs built with Django REST framework.\n They can be used with any API that exposes a supported schema format.\n\n\nFor example, \nthe Heroku platform API\n exposes a schema in the JSON\nHyperschema format. As a result, the Core API command line client and Python\nclient library can be \nused to interact with the Heroku API\n.\n\n\nClient-side Core API\n\n\nCore API\n is a document specification that can be used to describe APIs. It can\nbe used either server-side, as is done with REST framework's \nschema generation\n,\nor used client-side, as described here.\n\n\nWhen used client-side, Core API allows for \ndynamically driven client libraries\n\nthat can interact with any API that exposes a supported schema or hypermedia\nformat.\n\n\nUsing a dynamically driven client has a number of advantages over interacting\nwith an API by building HTTP requests directly.\n\n\nMore meaningful interaction\n\n\nAPI interactions are presented in a more meaningful way. You're working at\nthe application interface layer, rather than the network interface layer.\n\n\nResilience \n evolvability\n\n\nThe client determines what endpoints are available, what parameters exist\nagainst each particular endpoint, and how HTTP requests are formed.\n\n\nThis also allows for a degree of API evolvability. URLs can be modified\nwithout breaking existing clients, or more efficient encodings can be used\non-the-wire, with clients transparently upgrading.\n\n\nSelf-descriptive APIs\n\n\nA dynamically driven client is able to present documentation on the API to the\nend user. This documentation allows the user to discover the available endpoints\nand parameters, and better understand the API they are working with.\n\n\nBecause this documentation is driven by the API schema it will always be fully\nup to date with the most recently deployed version of the service.\n\n\n\n\nCommand line client\n\n\nThe command line client allows you to inspect and interact with any API that\nexposes a supported schema format.\n\n\nGetting started\n\n\nTo install the Core API command line client, use \npip\n.\n\n\nNote that the command-line client is a separate package to the\npython client library. Make sure to install \ncoreapi-cli\n.\n\n\n$ pip install coreapi-cli\n\n\n\nTo start inspecting and interacting with an API the schema must first be loaded\nfrom the network.\n\n\n$ coreapi get http://api.example.org/\n\nPastebin API \"http://127.0.0.1:8000/\"\n\nsnippets: {\n create(code, [title], [linenos], [language], [style])\n destroy(pk)\n highlight(pk)\n list([page])\n partial_update(pk, [title], [code], [linenos], [language], [style])\n retrieve(pk)\n update(pk, code, [title], [linenos], [language], [style])\n}\nusers: {\n list([page])\n retrieve(pk)\n}\n\n\n\nThis will then load the schema, displaying the resulting \nDocument\n. This\n\nDocument\n includes all the available interactions that may be made against the API.\n\n\nTo interact with the API, use the \naction\n command. This command requires a list\nof keys that are used to index into the link.\n\n\n$ coreapi action users list\n[\n {\n \"url\": \"http://127.0.0.1:8000/users/2/\",\n \"id\": 2,\n \"username\": \"aziz\",\n \"snippets\": []\n },\n ...\n]\n\n\n\nTo inspect the underlying HTTP request and response, use the \n--debug\n flag.\n\n\n$ coreapi action users list --debug\n\n GET /users/ HTTP/1.1\n\n Accept: application/vnd.coreapi+json, */*\n\n Authorization: Basic bWF4Om1heA==\n\n Host: 127.0.0.1\n\n User-Agent: coreapi\n\n 200 OK\n\n Allow: GET, HEAD, OPTIONS\n\n Content-Type: application/json\n\n Date: Thu, 30 Jun 2016 10:51:46 GMT\n\n Server: WSGIServer/0.1 Python/2.7.10\n\n Vary: Accept, Cookie\n\n\n\n [{\"url\":\"http://127.0.0.1/users/2/\",\"id\":2,\"username\":\"aziz\",\"snippets\":[]},{\"url\":\"http://127.0.0.1/users/3/\",\"id\":3,\"username\":\"amy\",\"snippets\":[\"http://127.0.0.1/snippets/3/\"]},{\"url\":\"http://127.0.0.1/users/4/\",\"id\":4,\"username\":\"max\",\"snippets\":[\"http://127.0.0.1/snippets/4/\",\"http://127.0.0.1/snippets/5/\",\"http://127.0.0.1/snippets/6/\",\"http://127.0.0.1/snippets/7/\"]},{\"url\":\"http://127.0.0.1/users/5/\",\"id\":5,\"username\":\"jose\",\"snippets\":[]},{\"url\":\"http://127.0.0.1/users/6/\",\"id\":6,\"username\":\"admin\",\"snippets\":[\"http://127.0.0.1/snippets/1/\",\"http://127.0.0.1/snippets/2/\"]}]\n\n[\n ...\n]\n\n\n\nSome actions may include optional or required parameters.\n\n\n$ coreapi action users create --param username=example\n\n\n\nWhen using \n--param\n, the type of the input will be determined automatically.\n\n\nIf you want to be more explicit about the parameter type then use \n--data\n for\nany null, numeric, boolean, list, or object inputs, and use \n--string\n for string inputs.\n\n\n$ coreapi action users edit --string username=tomchristie --data is_admin=true\n\n\n\nAuthentication \n headers\n\n\nThe \ncredentials\n command is used to manage the request \nAuthentication:\n header.\nAny credentials added are always linked to a particular domain, so as to ensure\nthat credentials are not leaked across differing APIs.\n\n\nThe format for adding a new credential is:\n\n\n$ coreapi credentials add \ndomain\n \ncredentials string\n\n\n\n\nFor instance:\n\n\n$ coreapi credentials add api.example.org \"Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\"\n\n\n\nThe optional \n--auth\n flag also allows you to add specific types of authentication,\nhandling the encoding for you. Currently only \n\"basic\"\n is supported as an option here.\nFor example:\n\n\n$ coreapi credentials add api.example.org tomchristie:foobar --auth basic\n\n\n\nYou can also add specific request headers, using the \nheaders\n command:\n\n\n$ coreapi headers add api.example.org x-api-version 2\n\n\n\nFor more information and a listing of the available subcommands use \ncoreapi\ncredentials --help\n or \ncoreapi headers --help\n.\n\n\nCodecs\n\n\nBy default the command line client only includes support for reading Core JSON\nschemas, however it includes a plugin system for installing additional codecs.\n\n\n$ pip install openapi-codec jsonhyperschema-codec hal-codec\n$ coreapi codecs show\nCodecs\ncorejson application/vnd.coreapi+json encoding, decoding\nhal application/hal+json encoding, decoding\nopenapi application/openapi+json encoding, decoding\njsonhyperschema application/schema+json decoding\njson application/json data\ntext text/* data\n\n\n\nUtilities\n\n\nThe command line client includes functionality for bookmarking API URLs\nunder a memorable name. For example, you can add a bookmark for the\nexisting API, like so...\n\n\n$ coreapi bookmarks add accountmanagement\n\n\n\nThere is also functionality for navigating forward or backward through the\nhistory of which API URLs have been accessed.\n\n\n$ coreapi history show\n$ coreapi history back\n\n\n\nFor more information and a listing of the available subcommands use\n\ncoreapi bookmarks --help\n or \ncoreapi history --help\n.\n\n\nOther commands\n\n\nTo display the current \nDocument\n:\n\n\n$ coreapi show\n\n\n\nTo reload the current \nDocument\n from the network:\n\n\n$ coreapi reload\n\n\n\nTo load a schema file from disk:\n\n\n$ coreapi load my-api-schema.json --format corejson\n\n\n\nTo dump the current document to console in a given format:\n\n\n$ coreapi dump --format openapi\n\n\n\nTo remove the current document, along with all currently saved history,\ncredentials, headers and bookmarks:\n\n\n$ coreapi clear\n\n\n\n\n\nPython client library\n\n\nThe \ncoreapi\n Python package allows you to programmatically interact with any\nAPI that exposes a supported schema format.\n\n\nGetting started\n\n\nYou'll need to install the \ncoreapi\n package using \npip\n before you can get\nstarted.\n\n\n$ pip install coreapi\n\n\n\nIn order to start working with an API, we first need a \nClient\n instance. The\nclient holds any configuration around which codecs and transports are supported\nwhen interacting with an API, which allows you to provide for more advanced\nkinds of behaviour.\n\n\nimport coreapi\nclient = coreapi.Client()\n\n\n\nOnce we have a \nClient\n instance, we can fetch an API schema from the network.\n\n\nschema = client.get('https://api.example.org/')\n\n\n\nThe object returned from this call will be a \nDocument\n instance, which is\na representation of the API schema.\n\n\nAuthentication\n\n\nTypically you'll also want to provide some authentication credentials when\ninstantiating the client.\n\n\nToken authentication\n\n\nThe \nTokenAuthentication\n class can be used to support REST framework's built-in\n\nTokenAuthentication\n, as well as OAuth and JWT schemes.\n\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT'\n token='\ntoken\n'\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nWhen using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client.\n\n\nA suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint\n\n\nFor example, using the \"Django REST framework JWT\" package\n\n\nclient = coreapi.Client()\nschema = client.get('https://api.example.org/')\n\naction = ['api-token-auth', 'obtain-token']\nparams = {username: \"example\", email: \"example@example.com\"}\nresult = client.action(schema, action, params)\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT',\n token=result['token']\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nBasic authentication\n\n\nThe \nBasicAuthentication\n class can be used to support HTTP Basic Authentication.\n\n\nauth = coreapi.auth.BasicAuthentication(\n username='\nusername\n',\n password='\npassword\n'\n)\nclient = coreapi.Client(auth=auth)\n\n\n\nInteracting with the API\n\n\nNow that we have a client and have fetched our schema \nDocument\n, we can now\nstart to interact with the API:\n\n\nusers = client.action(schema, ['users', 'list'])\n\n\n\nSome endpoints may include named parameters, which might be either optional or required:\n\n\nnew_user = client.action(schema, ['users', 'create'], params={\"username\": \"max\"})\n\n\n\nCodecs\n\n\nCodecs are responsible for encoding or decoding Documents.\n\n\nThe decoding process is used by a client to take a bytestring of an API schema\ndefinition, and returning the Core API \nDocument\n that represents that interface.\n\n\nA codec should be associated with a particular media type, such as \n'application/coreapi+json'\n.\n\n\nThis media type is used by the server in the response \nContent-Type\n header,\nin order to indicate what kind of data is being returned in the response.\n\n\nConfiguring codecs\n\n\nThe codecs that are available can be configured when instantiating a client.\nThe keyword argument used here is \ndecoders\n, because in the context of a\nclient the codecs are only for \ndecoding\n responses.\n\n\nIn the following example we'll configure a client to only accept \nCore JSON\n\nand \nJSON\n responses. This will allow us to receive and decode a Core JSON schema,\nand subsequently to receive JSON responses made against the API.\n\n\nfrom coreapi import codecs, Client\n\ndecoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()]\nclient = Client(decoders=decoders)\n\n\n\nLoading and saving schemas\n\n\nYou can use a codec directly, in order to load an existing schema definition,\nand return the resulting \nDocument\n.\n\n\ninput_file = open('my-api-schema.json', 'rb')\nschema_definition = input_file.read()\ncodec = codecs.CoreJSONCodec()\nschema = codec.load(schema_definition)\n\n\n\nYou can also use a codec directly to generate a schema definition given a \nDocument\n instance:\n\n\nschema_definition = codec.dump(schema)\noutput_file = open('my-api-schema.json', 'rb')\noutput_file.write(schema_definition)\n\n\n\nTransports\n\n\nTransports are responsible for making network requests. The set of transports\nthat a client has installed determines which network protocols it is able to\nsupport.\n\n\nCurrently the \ncoreapi\n library only includes an HTTP/HTTPS transport, but\nother protocols can also be supported.\n\n\nConfiguring transports\n\n\nThe behavior of the network layer can be customized by configuring the\ntransports that the client is instantiated with.\n\n\nimport requests\nfrom coreapi import transports, Client\n\ncredentials = {'api.example.org': 'Token 3bd44a009d16ff'}\ntransports = transports.HTTPTransport(credentials=credentials)\nclient = Client(transports=transports)\n\n\n\nMore complex customizations can also be achieved, for example modifying the\nunderlying \nrequests.Session\n instance to \nattach transport adaptors\n\nthat modify the outgoing requests.\n\n\n\n\nJavaScript Client Library\n\n\nThe JavaScript client library allows you to interact with your API either from a browser, or using node.\n\n\nInstalling the JavaScript client\n\n\nThere are two separate JavaScript resources that you need to include in your HTML pages in order to use the JavaScript client library. These are a static \ncoreapi.js\n file, which contains the code for the dynamic client library, and a templated \nschema.js\n resource, which exposes your API schema.\n\n\nFirst, install the API documentation views. These will include the schema resource that'll allow you to load the schema directly from an HTML page, without having to make an asynchronous AJAX call.\n\n\nfrom rest_framework.documentation import include_docs_urls\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title='My API service'))\n]\n\n\n\nOnce the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed.\n\n\n!--\n Load the CoreAPI library and the API schema.\n\n /static/rest_framework/js/coreapi-0.1.0.js\n /docs/schema.js\n--\n\n{% load staticfiles %}\n\nscript src=\"{% static 'rest_framework/js/coreapi-0.1.0.js' %}\"\n/script\n\n\nscript src=\"{% url 'api-docs:schema-js' %}\"\n/script\n\n\n\n\nThe \ncoreapi\n library, and the \nschema\n object will now both be available on the \nwindow\n instance.\n\n\nconst coreapi = window.coreapi\nconst schema = window.schema\n\n\n\nInstantiating a client\n\n\nIn order to interact with the API you'll need a client instance.\n\n\nvar client = coreapi.Client()\n\n\n\nTypically you'll also want to provide some authentication credentials when\ninstantiating the client.\n\n\nSession authentication\n\n\nThe \nSessionAuthentication\n class allows session cookies to provide the user\nauthentication. You'll want to provide a standard HTML login flow, to allow\nthe user to login, and then instantiate a client using session authentication:\n\n\nlet auth = coreapi.auth.SessionAuthentication({\n csrfCookieName: 'csrftoken',\n csrfHeaderName: 'X-CSRFToken'\n})\nlet client = coreapi.Client({auth: auth})\n\n\n\nThe authentication scheme will handle including a CSRF header in any outgoing\nrequests for unsafe HTTP methods.\n\n\nToken authentication\n\n\nThe \nTokenAuthentication\n class can be used to support REST framework's built-in\n\nTokenAuthentication\n, as well as OAuth and JWT schemes.\n\n\nlet auth = coreapi.auth.TokenAuthentication({\n scheme: 'JWT'\n token: '\ntoken\n'\n})\nlet client = coreapi.Client({auth: auth})\n\n\n\nWhen using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client.\n\n\nA suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint\n\n\nFor example, using the \"Django REST framework JWT\" package\n\n\n// Setup some globally accessible state\nwindow.client = coreapi.Client()\nwindow.loggedIn = false\n\nfunction loginUser(username, password) {\n let action = [\"api-token-auth\", \"obtain-token\"]\n let params = {username: \"example\", email: \"example@example.com\"}\n client.action(schema, action, params).then(function(result) {\n // On success, instantiate an authenticated client.\n let auth = window.coreapi.auth.TokenAuthentication({\n scheme: 'JWT',\n token: result['token']\n })\n window.client = coreapi.Client({auth: auth})\n window.loggedIn = true\n }).catch(function (error) {\n // Handle error case where eg. user provides incorrect credentials.\n })\n}\n\n\n\nBasic authentication\n\n\nThe \nBasicAuthentication\n class can be used to support HTTP Basic Authentication.\n\n\nlet auth = coreapi.auth.BasicAuthentication({\n username: '\nusername\n',\n password: '\npassword\n'\n})\nlet client = coreapi.Client({auth: auth})\n\n\n\nUsing the client\n\n\nMaking requests:\n\n\nlet action = [\"users\", \"list\"]\nclient.action(schema, action).then(function(result) {\n // Return value is in 'result'\n})\n\n\n\nIncluding parameters:\n\n\nlet action = [\"users\", \"create\"]\nlet params = {username: \"example\", email: \"example@example.com\"}\nclient.action(schema, action, params).then(function(result) {\n // Return value is in 'result'\n})\n\n\n\nHandling errors:\n\n\nclient.action(schema, action, params).then(function(result) {\n // Return value is in 'result'\n}).catch(function (error) {\n // Error value is in 'error'\n})\n\n\n\nInstallation with node\n\n\nThe coreapi package is available on NPM.\n\n\n$ npm install coreapi\n$ node\nconst coreapi = require('coreapi')\n\n\n\nYou'll either want to include the API schema in your codebase directly, by copying it from the \nschema.js\n resource, or else load the schema asynchronously. For example:\n\n\nlet client = new coreapi.Client()\nlet schema = null\nclient.get(\"https://api.example.org/\").then(function(data) {\n // Load a CoreJSON API schema.\n schema = data\n console.log('schema loaded')\n})", "title": "API Clients" }, { @@ -4032,9 +4047,29 @@ }, { "location": "/topics/api-clients/#getting-started_1", - "text": "You'll need to install the coreapi package using pip before you can get\nstarted. $ pip install coreapi In order to start working with an API, we first need a Client instance. The\nclient holds any configuration around which codecs and transports are supported\nwhen interacting with an API, which allows you to provide for more advanced\nkinds of behaviour. import coreapi\nclient = coreapi.Client() Once we have a Client instance, we can fetch an API schema from the network. schema = client.get('https://api.example.org/') The object returned from this call will be a Document instance, which is\nthe internal representation of the interface that we are interacting with. Now that we have our schema Document , we can now start to interact with the API: users = client.action(schema, ['users', 'list']) Some endpoints may include named parameters, which might be either optional or required: new_user = client.action(schema, ['users', 'create'], params={\"username\": \"max\"})", + "text": "You'll need to install the coreapi package using pip before you can get\nstarted. $ pip install coreapi In order to start working with an API, we first need a Client instance. The\nclient holds any configuration around which codecs and transports are supported\nwhen interacting with an API, which allows you to provide for more advanced\nkinds of behaviour. import coreapi\nclient = coreapi.Client() Once we have a Client instance, we can fetch an API schema from the network. schema = client.get('https://api.example.org/') The object returned from this call will be a Document instance, which is\na representation of the API schema.", "title": "Getting started" }, + { + "location": "/topics/api-clients/#authentication", + "text": "Typically you'll also want to provide some authentication credentials when\ninstantiating the client.", + "title": "Authentication" + }, + { + "location": "/topics/api-clients/#token-authentication", + "text": "The TokenAuthentication class can be used to support REST framework's built-in TokenAuthentication , as well as OAuth and JWT schemes. auth = coreapi.auth.TokenAuthentication(\n scheme='JWT'\n token=' token '\n)\nclient = coreapi.Client(auth=auth) When using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client. A suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint For example, using the \"Django REST framework JWT\" package client = coreapi.Client()\nschema = client.get('https://api.example.org/')\n\naction = ['api-token-auth', 'obtain-token']\nparams = {username: \"example\", email: \"example@example.com\"}\nresult = client.action(schema, action, params)\n\nauth = coreapi.auth.TokenAuthentication(\n scheme='JWT',\n token=result['token']\n)\nclient = coreapi.Client(auth=auth)", + "title": "Token authentication" + }, + { + "location": "/topics/api-clients/#basic-authentication", + "text": "The BasicAuthentication class can be used to support HTTP Basic Authentication. auth = coreapi.auth.BasicAuthentication(\n username=' username ',\n password=' password '\n)\nclient = coreapi.Client(auth=auth)", + "title": "Basic authentication" + }, + { + "location": "/topics/api-clients/#interacting-with-the-api", + "text": "Now that we have a client and have fetched our schema Document , we can now\nstart to interact with the API: users = client.action(schema, ['users', 'list']) Some endpoints may include named parameters, which might be either optional or required: new_user = client.action(schema, ['users', 'create'], params={\"username\": \"max\"})", + "title": "Interacting with the API" + }, { "location": "/topics/api-clients/#codecs_1", "text": "Codecs are responsible for encoding or decoding Documents. The decoding process is used by a client to take a bytestring of an API schema\ndefinition, and returning the Core API Document that represents that interface. A codec should be associated with a particular media type, such as 'application/coreapi+json' . This media type is used by the server in the response Content-Type header,\nin order to indicate what kind of data is being returned in the response.", @@ -4057,9 +4092,49 @@ }, { "location": "/topics/api-clients/#configuring-transports", - "text": "The behaviour of the network layer can be customized by configuring the\ntransports that the client is instantiated with. import requests\nfrom coreapi import transports, Client\n\ncredentials = {'api.example.org': 'Token 3bd44a009d16ff'}\ntransports = transports.HTTPTransport(credentials=credentials)\nclient = Client(transports=transports) More complex customizations can also be achieved, for example modifying the\nunderlying requests.Session instance to attach transport adaptors \nthat modify the outgoing requests.", + "text": "The behavior of the network layer can be customized by configuring the\ntransports that the client is instantiated with. import requests\nfrom coreapi import transports, Client\n\ncredentials = {'api.example.org': 'Token 3bd44a009d16ff'}\ntransports = transports.HTTPTransport(credentials=credentials)\nclient = Client(transports=transports) More complex customizations can also be achieved, for example modifying the\nunderlying requests.Session instance to attach transport adaptors \nthat modify the outgoing requests.", "title": "Configuring transports" }, + { + "location": "/topics/api-clients/#javascript-client-library", + "text": "The JavaScript client library allows you to interact with your API either from a browser, or using node.", + "title": "JavaScript Client Library" + }, + { + "location": "/topics/api-clients/#installing-the-javascript-client", + "text": "There are two separate JavaScript resources that you need to include in your HTML pages in order to use the JavaScript client library. These are a static coreapi.js file, which contains the code for the dynamic client library, and a templated schema.js resource, which exposes your API schema. First, install the API documentation views. These will include the schema resource that'll allow you to load the schema directly from an HTML page, without having to make an asynchronous AJAX call. from rest_framework.documentation import include_docs_urls\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title='My API service'))\n] Once the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed. !--\n Load the CoreAPI library and the API schema.\n\n /static/rest_framework/js/coreapi-0.1.0.js\n /docs/schema.js\n-- \n{% load staticfiles %} script src=\"{% static 'rest_framework/js/coreapi-0.1.0.js' %}\" /script script src=\"{% url 'api-docs:schema-js' %}\" /script The coreapi library, and the schema object will now both be available on the window instance. const coreapi = window.coreapi\nconst schema = window.schema", + "title": "Installing the JavaScript client" + }, + { + "location": "/topics/api-clients/#instantiating-a-client", + "text": "In order to interact with the API you'll need a client instance. var client = coreapi.Client() Typically you'll also want to provide some authentication credentials when\ninstantiating the client.", + "title": "Instantiating a client" + }, + { + "location": "/topics/api-clients/#session-authentication", + "text": "The SessionAuthentication class allows session cookies to provide the user\nauthentication. You'll want to provide a standard HTML login flow, to allow\nthe user to login, and then instantiate a client using session authentication: let auth = coreapi.auth.SessionAuthentication({\n csrfCookieName: 'csrftoken',\n csrfHeaderName: 'X-CSRFToken'\n})\nlet client = coreapi.Client({auth: auth}) The authentication scheme will handle including a CSRF header in any outgoing\nrequests for unsafe HTTP methods.", + "title": "Session authentication" + }, + { + "location": "/topics/api-clients/#token-authentication_1", + "text": "The TokenAuthentication class can be used to support REST framework's built-in TokenAuthentication , as well as OAuth and JWT schemes. let auth = coreapi.auth.TokenAuthentication({\n scheme: 'JWT'\n token: ' token '\n})\nlet client = coreapi.Client({auth: auth}) When using TokenAuthentication you'll probably need to implement a login flow\nusing the CoreAPI client. A suggested pattern for this would be to initially make an unauthenticated client\nrequest to an \"obtain token\" endpoint For example, using the \"Django REST framework JWT\" package // Setup some globally accessible state\nwindow.client = coreapi.Client()\nwindow.loggedIn = false\n\nfunction loginUser(username, password) {\n let action = [\"api-token-auth\", \"obtain-token\"]\n let params = {username: \"example\", email: \"example@example.com\"}\n client.action(schema, action, params).then(function(result) {\n // On success, instantiate an authenticated client.\n let auth = window.coreapi.auth.TokenAuthentication({\n scheme: 'JWT',\n token: result['token']\n })\n window.client = coreapi.Client({auth: auth})\n window.loggedIn = true\n }).catch(function (error) {\n // Handle error case where eg. user provides incorrect credentials.\n })\n}", + "title": "Token authentication" + }, + { + "location": "/topics/api-clients/#basic-authentication_1", + "text": "The BasicAuthentication class can be used to support HTTP Basic Authentication. let auth = coreapi.auth.BasicAuthentication({\n username: ' username ',\n password: ' password '\n})\nlet client = coreapi.Client({auth: auth})", + "title": "Basic authentication" + }, + { + "location": "/topics/api-clients/#using-the-client", + "text": "Making requests: let action = [\"users\", \"list\"]\nclient.action(schema, action).then(function(result) {\n // Return value is in 'result'\n}) Including parameters: let action = [\"users\", \"create\"]\nlet params = {username: \"example\", email: \"example@example.com\"}\nclient.action(schema, action, params).then(function(result) {\n // Return value is in 'result'\n}) Handling errors: client.action(schema, action, params).then(function(result) {\n // Return value is in 'result'\n}).catch(function (error) {\n // Error value is in 'error'\n})", + "title": "Using the client" + }, + { + "location": "/topics/api-clients/#installation-with-node", + "text": "The coreapi package is available on NPM. $ npm install coreapi\n$ node\nconst coreapi = require('coreapi') You'll either want to include the API schema in your codebase directly, by copying it from the schema.js resource, or else load the schema asynchronously. For example: let client = new coreapi.Client()\nlet schema = null\nclient.get(\"https://api.example.org/\").then(function(data) {\n // Load a CoreJSON API schema.\n schema = data\n console.log('schema loaded')\n})", + "title": "Installation with node" + }, { "location": "/topics/internationalization/", "text": "Internationalization\n\n\n\n\nSupporting internationalization is not optional. It must be a core feature.\n\n\n \nJannis Leidel, speaking at Django Under the Hood, 2015\n.\n\n\n\n\nREST framework ships with translatable error messages. You can make these appear in your language enabling \nDjango's standard translation mechanisms\n.\n\n\nDoing so will allow you to:\n\n\n\n\nSelect a language other than English as the default, using the standard \nLANGUAGE_CODE\n Django setting.\n\n\nAllow clients to choose a language themselves, using the \nLocaleMiddleware\n included with Django. A typical usage for API clients would be to include an \nAccept-Language\n request header.\n\n\n\n\nEnabling internationalized APIs\n\n\nYou can change the default language by using the standard Django \nLANGUAGE_CODE\n setting:\n\n\nLANGUAGE_CODE = \"es-es\"\n\n\n\nYou can turn on per-request language requests by adding \nLocalMiddleware\n to your \nMIDDLEWARE_CLASSES\n setting:\n\n\nMIDDLEWARE_CLASSES = [\n ...\n 'django.middleware.locale.LocaleMiddleware'\n]\n\n\n\nWhen per-request internationalization is enabled, client requests will respect the \nAccept-Language\n header where possible. For example, let's make a request for an unsupported media type:\n\n\nRequest\n\n\nGET /api/users HTTP/1.1\nAccept: application/xml\nAccept-Language: es-es\nHost: example.org\n\n\n\nResponse\n\n\nHTTP/1.0 406 NOT ACCEPTABLE\n\n{\"detail\": \"No se ha podido satisfacer la solicitud de cabecera de Accept.\"}\n\n\n\nREST framework includes these built-in translations both for standard exception cases, and for serializer validation errors.\n\n\nNote that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example \n400 Bad Request\n response body might look like this:\n\n\n{\"detail\": {\"username\": [\"Esse campo deve ser unico.\"]}}\n\n\n\nIf you want to use different string for parts of the response such as \ndetail\n and \nnon_field_errors\n then you can modify this behavior by using a \ncustom exception handler\n.\n\n\nSpecifying the set of supported languages.\n\n\nBy default all available languages will be supported.\n\n\nIf you only wish to support a subset of the available languages, use Django's standard \nLANGUAGES\n setting:\n\n\nLANGUAGES = [\n ('de', _('German')),\n ('en', _('English')),\n]\n\n\n\nAdding new translations\n\n\nREST framework translations are managed online using \nTransifex\n. You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package.\n\n\nSometimes you may need to add translation strings to your project locally. You may need to do this if:\n\n\n\n\nYou want to use REST Framework in a language which has not been translated yet on Transifex.\n\n\nYour project includes custom error messages, which are not part of REST framework's default translation strings.\n\n\n\n\nTranslating a new language locally\n\n\nThis guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading \nDjango's translation docs\n.\n\n\nIf you're translating a new language you'll need to translate the existing REST framework error messages:\n\n\n\n\n\n\nMake a new folder where you want to store the internationalization resources. Add this path to your \nLOCALE_PATHS\n setting.\n\n\n\n\n\n\nNow create a subfolder for the language you want to translate. The folder should be named using \nlocale name\n notation. For example: \nde\n, \npt_BR\n, \nes_AR\n.\n\n\n\n\n\n\nNow copy the \nbase translations file\n from the REST framework source code into your translations folder.\n\n\n\n\n\n\nEdit the \ndjango.po\n file you've just copied, translating all the error messages.\n\n\n\n\n\n\nRun \nmanage.py compilemessages -l pt_BR\n to make the translations \navailable for Django to use. You should see a message like \nprocessing file django.po in \n...\n/locale/pt_BR/LC_MESSAGES\n.\n\n\n\n\n\n\nRestart your development server to see the changes take effect.\n\n\n\n\n\n\nIf you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source \ndjango.po\n file into a \nLOCALE_PATHS\n folder, and can instead simply run Django's standard \nmakemessages\n process.\n\n\nHow the language is determined\n\n\nIf you want to allow per-request language preferences you'll need to include \ndjango.middleware.locale.LocaleMiddleware\n in your \nMIDDLEWARE_CLASSES\n setting.\n\n\nYou can find more information on how the language preference is determined in the \nDjango documentation\n. For reference, the method is:\n\n\n\n\nFirst, it looks for the language prefix in the requested URL.\n\n\nFailing that, it looks for the \nLANGUAGE_SESSION_KEY\n key in the current user\u2019s session.\n\n\nFailing that, it looks for a cookie.\n\n\nFailing that, it looks at the \nAccept-Language\n HTTP header.\n\n\nFailing that, it uses the global \nLANGUAGE_CODE\n setting.\n\n\n\n\nFor API clients the most appropriate of these will typically be to use the \nAccept-Language\n header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an \nAccept-Language\n header for API clients rather than using language URL prefixes.", @@ -4447,7 +4522,7 @@ }, { "location": "/topics/tutorials-and-resources/", - "text": "Tutorials and Resources\n\n\nThere are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django REST Framework\n\n\nDjango REST Framework - An Introduction\n\n\nDjango REST Framework Tutorial\n\n\nDjango REST Framework Course\n\n\nBuilding a RESTful API with Django REST Framework\n\n\nGetting Started with Django REST Framework and AngularJS\n\n\nEnd to End Web App with Django REST Framework \n AngularJS\n\n\nStart Your API - Django REST Framework Part 1\n\n\nPermissions \n Authentication - Django REST Framework Part 2\n\n\nViewSets and Routers - Django REST Framework Part 3\n\n\nDjango REST Framework User Endpoint\n\n\nCheck Credentials Using Django REST Framework\n\n\nCreating a Production Ready API with Python and Django REST Framework \u2013 Part 1\n\n\nCreating a Production Ready API with Python and Django REST Framework \u2013 Part 2\n\n\n\n\nVideos\n\n\nTalks\n\n\n\n\nHow to Make a Full Fledged REST API with Django OAuth Toolkit\n\n\nDjango REST API - So Easy You Can Learn It in 25 Minutes\n\n\nTom Christie about Django Rest Framework at Django: Under The Hood\n\n\nDjango REST Framework: Schemas, Hypermedia \n Client Libraries\n\n\n\n\nTutorials\n\n\n\n\nDjango REST Framework Part 1\n\n\nDjango REST Framework in Your PJ's!\n\n\nBuilding a REST API Using Django \n Django REST Framework\n\n\nBlog API with Django REST Framework\n\n\nEmber and Django Part 1\n\n\nDjango REST Framework Image Upload Tutorial (with AngularJS)\n\n\nDjango REST Framework Tutorials\n\n\n\n\nArticles\n\n\n\n\nWeb API performance: Profiling Django REST Framework\n\n\nAPI Development with Django and Django REST Framework\n\n\nIntegrating Pandas, Django REST Framework and Bokeh\n\n\nControlling Uncertainty on Web Applications and APIs\n\n\nFull Text Search in Django REST Framework with Database Backends\n\n\nOAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends\n\n\nNested Resources with Django REST Framework\n\n\nImage Fields with Django REST Framework\n\n\nChatbot Using Django REST Framework + api.ai + Slack\u200a\u2014\u200aPart 1/3\n\n\nNew Django Admin with DRF and EmberJS... What are the News?\n\n\nBlog posts about Django REST Framework\n\n\n\n\nBooks\n\n\n\n\nHello Web App: Intermediate Concepts, Chapter 10\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework\n\n\nDRF-schema-adapter\n\n\n\n\nWant your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please \nsubmit a pull request\n or [email us][mailto:anna@django-rest-framework.org]!", + "text": "Tutorials and Resources\n\n\nThere are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here.\n\n\nTutorials\n\n\n\n\nBeginner's Guide to the Django REST Framework\n\n\nDjango REST Framework - An Introduction\n\n\nDjango REST Framework Tutorial\n\n\nDjango REST Framework Course\n\n\nBuilding a RESTful API with Django REST Framework\n\n\nGetting Started with Django REST Framework and AngularJS\n\n\nEnd to End Web App with Django REST Framework \n AngularJS\n\n\nStart Your API - Django REST Framework Part 1\n\n\nPermissions \n Authentication - Django REST Framework Part 2\n\n\nViewSets and Routers - Django REST Framework Part 3\n\n\nDjango REST Framework User Endpoint\n\n\nCheck Credentials Using Django REST Framework\n\n\nCreating a Production Ready API with Python and Django REST Framework \u2013 Part 1\n\n\nCreating a Production Ready API with Python and Django REST Framework \u2013 Part 2\n\n\n\n\nVideos\n\n\nTalks\n\n\n\n\nHow to Make a Full Fledged REST API with Django OAuth Toolkit\n\n\nDjango REST API - So Easy You Can Learn It in 25 Minutes\n\n\nTom Christie about Django Rest Framework at Django: Under The Hood\n\n\nDjango REST Framework: Schemas, Hypermedia \n Client Libraries\n\n\n\n\nTutorials\n\n\n\n\nDjango REST Framework Part 1\n\n\nDjango REST Framework in Your PJ's!\n\n\nBuilding a REST API Using Django \n Django REST Framework\n\n\nBlog API with Django REST Framework\n\n\nEmber and Django Part 1\n\n\nDjango REST Framework Image Upload Tutorial (with AngularJS)\n\n\nDjango REST Framework Tutorials\n\n\n\n\nArticles\n\n\n\n\nWeb API performance: Profiling Django REST Framework\n\n\nAPI Development with Django and Django REST Framework\n\n\nIntegrating Pandas, Django REST Framework and Bokeh\n\n\nControlling Uncertainty on Web Applications and APIs\n\n\nFull Text Search in Django REST Framework with Database Backends\n\n\nOAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends\n\n\nNested Resources with Django REST Framework\n\n\nImage Fields with Django REST Framework\n\n\nChatbot Using Django REST Framework + api.ai + Slack\u200a\u2014\u200aPart 1/3\n\n\nNew Django Admin with DRF and EmberJS... What are the News?\n\n\nBlog posts about Django REST Framework\n\n\n\n\nBooks\n\n\n\n\nHello Web App: Intermediate Concepts, Chapter 10\n\n\n\n\nDocumentations\n\n\n\n\nClassy Django REST Framework\n\n\nDRF-schema-adapter\n\n\n\n\nWant your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please \nsubmit a pull request\n or \nemail us\n!", "title": "Tutorials and Resources" }, { @@ -4487,7 +4562,7 @@ }, { "location": "/topics/tutorials-and-resources/#documentations", - "text": "Classy Django REST Framework DRF-schema-adapter Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please submit a pull request or [email us][mailto:anna@django-rest-framework.org]!", + "text": "Classy Django REST Framework DRF-schema-adapter Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please submit a pull request or email us !", "title": "Documentations" }, { @@ -4655,6 +4730,21 @@ "text": "The following issues still need to be addressed: Consider moving the repo into a proper GitHub organization . Ensure @jamie has back-up access to the django-rest-framework.org domain setup and admin. Document ownership of the live example API. Document ownership of the mailing list and IRC channel. Document ownership and management of the security mailing list.", "title": "Outstanding management & ownership issues" }, + { + "location": "/topics/jobs/", + "text": "Jobs\n\n\nLooking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of \nour sponsors are hiring\n.\n\n\nPlaces to look for Django REST Framework Jobs\n\n\n\n\nhttps://www.djangoproject.com/community/jobs/\n\n\nhttps://www.python.org/jobs/\n\n\nhttps://djangogigs.com\n\n\nhttps://djangojobs.net/jobs/\n\n\nhttp://djangojobbers.com\n\n\nhttps://www.indeed.com/q-Django-jobs.html\n\n\nhttp://stackoverflow.com/jobs/developer-jobs-using-django\n\n\nhttps://www.upwork.com/o/jobs/browse/skill/django-framework/\n\n\nhttps://www.technojobs.co.uk/django-jobs\n\n\nhttps://remoteok.io/remote-django-jobs\n\n\nhttps://www.remotepython.com/jobs/\n\n\n\n\nKnow of any other great resources for Django REST Framework jobs that are missing in our list? Please \nsubmit a pull request\n or \nemail us\n.\n\n\nWonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for \nREST Framework sponsorship\n yet.", + "title": "Jobs" + }, + { + "location": "/topics/jobs/#jobs", + "text": "Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of our sponsors are hiring .", + "title": "Jobs" + }, + { + "location": "/topics/jobs/#places-to-look-for-django-rest-framework-jobs", + "text": "https://www.djangoproject.com/community/jobs/ https://www.python.org/jobs/ https://djangogigs.com https://djangojobs.net/jobs/ http://djangojobbers.com https://www.indeed.com/q-Django-jobs.html http://stackoverflow.com/jobs/developer-jobs-using-django https://www.upwork.com/o/jobs/browse/skill/django-framework/ https://www.technojobs.co.uk/django-jobs https://remoteok.io/remote-django-jobs https://www.remotepython.com/jobs/ Know of any other great resources for Django REST Framework jobs that are missing in our list? Please submit a pull request or email us . Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for REST Framework sponsorship yet.", + "title": "Places to look for Django REST Framework Jobs" + }, { "location": "/topics/3.0-announcement/", "text": "Django REST framework 3.0\n\n\nThe 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.\n\n\nThis release is incremental in nature. There \nare\n some breaking API changes, and upgrading \nwill\n require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.\n\n\nThe difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.\n\n\n3.0 is the first of three releases that have been funded by our recent \nKickstarter campaign\n.\n\n\nAs ever, a huge thank you to our many \nwonderful sponsors\n. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.\n\n\n\n\nNew features\n\n\nNotable features of this new release include:\n\n\n\n\nPrintable representations on serializers that allow you to inspect exactly what fields are present on the instance.\n\n\nSimple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit \nModelSerializer\n class and the explicit \nSerializer\n class.\n\n\nA new \nBaseSerializer\n class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.\n\n\nA cleaner fields API including new classes such as \nListField\n and \nMultipleChoiceField\n.\n\n\nSuper simple default implementations\n for the generic views.\n\n\nSupport for overriding how validation errors are handled by your API.\n\n\nA metadata API that allows you to customize how \nOPTIONS\n requests are handled by your API.\n\n\nA more compact JSON output with unicode style encoding turned on by default.\n\n\nTemplated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.\n\n\n\n\nSignificant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two \nKickstarter stretch goals\n - \"Feature improvements\" and \"Admin interface\". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.\n\n\n\n\nREST framework: Under the hood.\n\n\nThis talk from the \nDjango: Under the Hood\n event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.\n\n\n\n\n\n\n\nBelow is an in-depth guide to the API changes and migration notes for 3.0.\n\n\nRequest objects\n\n\n.query_params\n properties.\nThe \n.data\n and \n\n\nThe usage of \nrequest.DATA\n and \nrequest.FILES\n is now pending deprecation in favor of a single \nrequest.data\n attribute that contains \nall\n the parsed data.\n\n\nHaving separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.\n\n\nYou may now pass all the request data to a serializer class in a single argument:\n\n\n# Do this...\nExampleSerializer(data=request.data)\n\n\n\nInstead of passing the files argument separately:\n\n\n# Don't do this...\nExampleSerializer(data=request.DATA, files=request.FILES)\n\n\n\nThe usage of \nrequest.QUERY_PARAMS\n is now pending deprecation in favor of the lowercased \nrequest.query_params\n.\n\n\n\n\nSerializers\n\n\nSingle-step object creation.\n\n\nPreviously the serializers used a two-step object creation, as follows:\n\n\n\n\nValidating the data would create an object instance. This instance would be available as \nserializer.object\n.\n\n\nCalling \nserializer.save()\n would then save the object instance to the database.\n\n\n\n\nThis style is in-line with how the \nModelForm\n class works in Django, but is problematic for a number of reasons:\n\n\n\n\nSome data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when \n.save()\n is called.\n\n\nInstantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. \nExampleModel.objects.create(...)\n. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.\n\n\nThe two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?\n\n\n\n\nWe now use single-step object creation, like so:\n\n\n\n\nValidating the data makes the cleaned data available as \nserializer.validated_data\n.\n\n\nCalling \nserializer.save()\n then saves and returns the new object instance.\n\n\n\n\nThe resulting API changes are further detailed below.\n\n\n.update()\n methods.\nThe \n.create()\n and \n\n\nThe \n.restore_object()\n method is now removed, and we instead have two separate methods, \n.create()\n and \n.update()\n. These methods work slightly different to the previous \n.restore_object()\n.\n\n\nWhen using the \n.create()\n and \n.update()\n methods you should both create \nand save\n the object instance. This is in contrast to the previous \n.restore_object()\n behavior that would instantiate the object but not save it.\n\n\nThese methods also replace the optional \n.save_object()\n method, which no longer exists.\n\n\nThe following example from the tutorial previously used \nrestore_object()\n to handle both creating and updating object instances.\n\n\ndef restore_object(self, attrs, instance=None):\n if instance:\n # Update existing instance\n instance.title = attrs.get('title', instance.title)\n instance.code = attrs.get('code', instance.code)\n instance.linenos = attrs.get('linenos', instance.linenos)\n instance.language = attrs.get('language', instance.language)\n instance.style = attrs.get('style', instance.style)\n return instance\n\n # Create new instance\n return Snippet(**attrs)\n\n\n\nThis would now be split out into two separate methods.\n\n\ndef update(self, instance, validated_data):\n instance.title = validated_data.get('title', instance.title)\n instance.code = validated_data.get('code', instance.code)\n instance.linenos = validated_data.get('linenos', instance.linenos)\n instance.language = validated_data.get('language', instance.language)\n instance.style = validated_data.get('style', instance.style)\n instance.save()\n return instance\n\ndef create(self, validated_data):\n return Snippet.objects.create(**validated_data)\n\n\n\nNote that these methods should return the newly created object instance.\n\n\n.object\n.\nUse \n.validated_data\n instead of \n\n\nYou must now use the \n.validated_data\n attribute if you need to inspect the data before saving, rather than using the \n.object\n attribute, which no longer exists.\n\n\nFor example the following code \nis no longer valid\n:\n\n\nif serializer.is_valid():\n name = serializer.object.name # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.object.user = request.user # Include the user when saving.\n serializer.save()\n\n\n\nInstead of using \n.object\n to inspect a partially constructed instance, you would now use \n.validated_data\n to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the \n.save()\n method as keyword arguments.\n\n\nThe corresponding code would now look like this:\n\n\nif serializer.is_valid():\n name = serializer.validated_data['name'] # Inspect validated field data.\n logging.info('Creating ticket \"%s\"' % name)\n serializer.save(user=request.user) # Include the user when saving.\n\n\n\nUsing \n.is_valid(raise_exception=True)\n\n\nThe \n.is_valid()\n method now takes an optional boolean flag, \nraise_exception\n.\n\n\nCalling \n.is_valid(raise_exception=True)\n will cause a \nValidationError\n to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.\n\n\nThe handling and formatting of error responses may be altered globally by using the \nEXCEPTION_HANDLER\n settings key.\n\n\nThis change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.\n\n\nUsing \nserializers.ValidationError\n.\n\n\nPreviously \nserializers.ValidationError\n error was simply a synonym for \ndjango.core.exceptions.ValidationError\n. This has now been altered so that it inherits from the standard \nAPIException\n base class.\n\n\nThe reason behind this is that Django's \nValidationError\n class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.\n\n\nFor most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the \nserializers.ValidationError\n exception class, and not Django's built-in exception.\n\n\nWe strongly recommend that you use the namespaced import style of \nimport serializers\n and not \nfrom serializers import ValidationError\n in order to avoid any potential confusion.\n\n\nChange to \nvalidate_\nfield_name\n.\n\n\nThe \nvalidate_\nfield_name\n method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:\n\n\ndef validate_score(self, attrs, source):\n if attrs['score'] % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return attrs\n\n\n\nThis is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.\n\n\ndef validate_score(self, value):\n if value % 10 != 0:\n raise serializers.ValidationError('This field should be a multiple of ten.')\n return value\n\n\n\nAny ad-hoc validation that applies to more than one field should go in the \n.validate(self, attrs)\n method as usual.\n\n\nBecause \n.validate_\nfield_name\n would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use \n.validate()\n instead.\n\n\nYou can either return \nnon_field_errors\n from the validate method by raising a simple \nValidationError\n\n\ndef validate(self, attrs):\n # serializer.errors == {'non_field_errors': ['A non field error']}\n raise serializers.ValidationError('A non field error')\n\n\n\nAlternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the \nValidationError\n, like so:\n\n\ndef validate(self, attrs):\n # serializer.errors == {'my_field': ['A field error']}\n raise serializers.ValidationError({'my_field': 'A field error'})\n\n\n\nThis ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.\n\n\nRemoval of \ntransform_\nfield_name\n.\n\n\nThe under-used \ntransform_\nfield_name\n on serializer classes is no longer provided. Instead you should just override \nto_representation()\n if you need to apply any modifications to the representation style.\n\n\nFor example:\n\n\ndef to_representation(self, instance):\n ret = super(UserSerializer, self).to_representation(instance)\n ret['username'] = ret['username'].lower()\n return ret\n\n\n\nDropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.\n\n\nIf you absolutely need to preserve \ntransform_\nfield_name\n behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:\n\n\nclass BaseModelSerializer(ModelSerializer):\n \"\"\"\n A custom ModelSerializer class that preserves 2.x style `transform_\nfield_name\n` behavior.\n \"\"\"\n def to_representation(self, instance):\n ret = super(BaseModelSerializer, self).to_representation(instance)\n for key, value in ret.items():\n method = getattr(self, 'transform_' + key, None)\n if method is not None:\n ret[key] = method(value)\n return ret\n\n\n\nDifferences between ModelSerializer validation and ModelForm.\n\n\nThis change also means that we no longer use the \n.full_clean()\n method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on \nModelSerializer\n classes that can't also be easily replicated on regular \nSerializer\n classes.\n\n\nFor the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.\n\n\nThe one difference that you do need to note is that the \n.clean()\n method will not be called as part of serializer validation, as it would be if using a \nModelForm\n. Use the serializer \n.validate()\n method to perform a final validation step on incoming data where required.\n\n\nThere may be some cases where you really do need to keep validation logic in the model \n.clean()\n method, and cannot instead separate it into the serializer \n.validate()\n. You can do so by explicitly instantiating a model instance in the \n.validate()\n method.\n\n\ndef validate(self, attrs):\n instance = ExampleModel(**attrs)\n instance.clean()\n return attrs\n\n\n\nAgain, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.\n\n\nWritable nested serialization.\n\n\nREST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:\n\n\n\n\nThere can be complex dependencies involved in order of saving multiple related model instances.\n\n\nIt's unclear what behavior the user should expect when related models are passed \nNone\n data.\n\n\nIt's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.\n\n\n\n\nUsing the \ndepth\n option on \nModelSerializer\n will now create \nread-only nested serializers\n by default.\n\n\nIf you try to use a writable nested serializer without writing a custom \ncreate()\n and/or \nupdate()\n method you'll see an assertion error when you attempt to save the serializer. For example:\n\n\n class ProfileSerializer(serializers.ModelSerializer):\n\n class Meta:\n\n model = Profile\n\n fields = ('address', 'phone')\n\n\n\n class UserSerializer(serializers.ModelSerializer):\n\n profile = ProfileSerializer()\n\n class Meta:\n\n model = User\n\n fields = ('username', 'email', 'profile')\n\n\n\n data = {\n\n 'username': 'lizzy',\n\n 'email': 'lizzy@example.com',\n\n 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}\n\n }\n\n\n\n serializer = UserSerializer(data=data)\n\n serializer.save()\nAssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.\n\n\n\nTo use writable nested serialization you'll want to declare a nested field on the serializer class, and write the \ncreate()\n and/or \nupdate()\n methods explicitly.\n\n\nclass UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'profile')\n\n def create(self, validated_data):\n profile_data = validated_data.pop('profile')\n user = User.objects.create(**validated_data)\n Profile.objects.create(user=user, **profile_data)\n return user\n\n\n\nThe single-step object creation makes this far simpler and more obvious than the previous \n.restore_object()\n behavior.\n\n\nPrintable serializer representations.\n\n\nSerializer instances now support a printable representation that allows you to inspect the fields present on the instance.\n\n\nFor instance, given the following example model:\n\n\nclass LocationRating(models.Model):\n location = models.CharField(max_length=100)\n rating = models.IntegerField()\n created_by = models.ForeignKey(User)\n\n\n\nLet's create a simple \nModelSerializer\n class corresponding to the \nLocationRating\n model.\n\n\nclass LocationRatingSerializer(serializer.ModelSerializer):\n class Meta:\n model = LocationRating\n\n\n\nWe can now inspect the serializer representation in the Django shell, using \npython manage.py shell\n...\n\n\n serializer = LocationRatingSerializer()\n\n print(serializer) # Or use `print serializer` in Python 2.x\nLocationRatingSerializer():\n id = IntegerField(label='ID', read_only=True)\n location = CharField(max_length=100)\n rating = IntegerField()\n created_by = PrimaryKeyRelatedField(queryset=User.objects.all())\n\n\n\nThe \nextra_kwargs\n option.\n\n\nThe \nwrite_only_fields\n option on \nModelSerializer\n has been moved to \nPendingDeprecation\n and replaced with a more generic \nextra_kwargs\n.\n\n\nclass MySerializer(serializer.ModelSerializer):\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'is_admin': {'write_only': True}\n }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.ModelSerializer):\n is_admin = serializers.BooleanField(write_only=True)\n\n class Meta:\n model = MyModel\n fields = ('id', 'email', 'notes', 'is_admin')\n\n\n\nThe \nread_only_fields\n option remains as a convenient shortcut for the more common case.\n\n\nChanges to \nHyperlinkedModelSerializer\n.\n\n\nThe \nview_name\n and \nlookup_field\n options have been moved to \nPendingDeprecation\n. They are no longer required, as you can use the \nextra_kwargs\n argument instead:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')\n extra_kwargs = {\n 'url': {'lookup_field': 'uuid'}\n }\n\n\n\nAlternatively, specify the field explicitly on the serializer class:\n\n\nclass MySerializer(serializer.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='mymodel-detail',\n lookup_field='uuid'\n )\n\n class Meta:\n model = MyModel\n fields = ('url', 'email', 'notes', 'is_admin')\n\n\n\nFields for model methods and properties.\n\n\nWith \nModelSerializer\n you can now specify field names in the \nfields\n option that refer to model methods or properties. For example, suppose you have the following model:\n\n\nclass Invitation(models.Model):\n created = models.DateTimeField()\n to_email = models.EmailField()\n message = models.CharField(max_length=1000)\n\n def expiry_date(self):\n return self.created + datetime.timedelta(days=30)\n\n\n\nYou can include \nexpiry_date\n as a field option on a \nModelSerializer\n class.\n\n\nclass InvitationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Invitation\n fields = ('to_email', 'message', 'expiry_date')\n\n\n\nThese fields will be mapped to \nserializers.ReadOnlyField()\n instances.\n\n\n serializer = InvitationSerializer()\n\n print repr(serializer)\nInvitationSerializer():\n to_email = EmailField(max_length=75)\n message = CharField(max_length=1000)\n expiry_date = ReadOnlyField()\n\n\n\nThe \nListSerializer\n class.\n\n\nThe \nListSerializer\n class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.\n\n\nclass MultipleUserSerializer(ListSerializer):\n child = UserSerializer()\n\n\n\nYou can also still use the \nmany=True\n argument to serializer classes. It's worth noting that \nmany=True\n argument transparently creates a \nListSerializer\n instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.\n\n\nYou will typically want to \ncontinue to use the existing \nmany=True\n flag\n rather than declaring \nListSerializer\n classes explicitly, but declaring the classes explicitly can be useful if you need to write custom \ncreate\n or \nupdate\n methods for bulk updates, or provide for other custom behavior.\n\n\nSee also the new \nListField\n class, which validates input in the same way, but does not include the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nBaseSerializer\n class.\n\n\nREST framework now includes a simple \nBaseSerializer\n class that can be used to easily support alternative serialization and deserialization styles.\n\n\nThis class implements the same basic API as the \nSerializer\n class:\n\n\n\n\n.data\n - Returns the outgoing primitive representation.\n\n\n.is_valid()\n - Deserializes and validates incoming data.\n\n\n.validated_data\n - Returns the validated incoming data.\n\n\n.errors\n - Returns an errors during validation.\n\n\n.save()\n - Persists the validated data into an object instance.\n\n\n\n\nThere are four methods that can be overridden, depending on what functionality you want the serializer class to support:\n\n\n\n\n.to_representation()\n - Override this to support serialization, for read operations.\n\n\n.to_internal_value()\n - Override this to support deserialization, for write operations.\n\n\n.create()\n and \n.update()\n - Override either or both of these to support saving instances.\n\n\n\n\nBecause this class provides the same interface as the \nSerializer\n class, you can use it with the existing generic class-based views exactly as you would for a regular \nSerializer\n or \nModelSerializer\n.\n\n\nThe only difference you'll notice when doing so is the \nBaseSerializer\n classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.\n\n\nRead-only \nBaseSerializer\n classes.\n\n\nTo implement a read-only serializer using the \nBaseSerializer\n class, we just need to override the \n.to_representation()\n method. Let's take a look at an example using a simple Django model:\n\n\nclass HighScore(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n player_name = models.CharField(max_length=10)\n score = models.IntegerField()\n\n\n\nIt's simple to create a read-only serializer for converting \nHighScore\n instances into primitive data types.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n\n\nWe can now use this class to serialize single \nHighScore\n instances:\n\n\n@api_view(['GET'])\ndef high_score(request, pk):\n instance = HighScore.objects.get(pk=pk)\n serializer = HighScoreSerializer(instance)\n return Response(serializer.data)\n\n\n\nOr use it to serialize multiple instances:\n\n\n@api_view(['GET'])\ndef all_high_scores(request):\n queryset = HighScore.objects.order_by('-score')\n serializer = HighScoreSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n\nRead-write \nBaseSerializer\n classes.\n\n\nTo create a read-write serializer we first need to implement a \n.to_internal_value()\n method. This method returns the validated values that will be used to construct the object instance, and may raise a \nValidationError\n if the supplied data is in an incorrect format.\n\n\nOnce you've implemented \n.to_internal_value()\n, the basic validation API will be available on the serializer, and you will be able to use \n.is_valid()\n, \n.validated_data\n and \n.errors\n.\n\n\nIf you want to also support \n.save()\n you'll need to also implement either or both of the \n.create()\n and \n.update()\n methods.\n\n\nHere's a complete example of our previous \nHighScoreSerializer\n, that's been updated to support both read and write operations.\n\n\nclass HighScoreSerializer(serializers.BaseSerializer):\n def to_internal_value(self, data):\n score = data.get('score')\n player_name = data.get('player_name')\n\n # Perform the data validation.\n if not score:\n raise ValidationError({\n 'score': 'This field is required.'\n })\n if not player_name:\n raise ValidationError({\n 'player_name': 'This field is required.'\n })\n if len(player_name) \n 10:\n raise ValidationError({\n 'player_name': 'May not be more than 10 characters.'\n })\n\n # Return the validated values. This will be available as\n # the `.validated_data` property.\n return {\n 'score': int(score),\n 'player_name': player_name\n }\n\n def to_representation(self, obj):\n return {\n 'score': obj.score,\n 'player_name': obj.player_name\n }\n\n def create(self, validated_data):\n return HighScore.objects.create(**validated_data)\n\n\n\nCreating new generic serializers with \nBaseSerializer\n.\n\n\nThe \nBaseSerializer\n class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.\n\n\nThe following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.\n\n\nclass ObjectSerializer(serializers.BaseSerializer):\n \"\"\"\n A read-only serializer that coerces arbitrary complex objects\n into primitive representations.\n \"\"\"\n def to_representation(self, obj):\n for attribute_name in dir(obj):\n attribute = getattr(obj, attribute_name)\n if attribute_name('_'):\n # Ignore private attributes.\n pass\n elif hasattr(attribute, '__call__'):\n # Ignore methods and other callables.\n pass\n elif isinstance(attribute, (str, int, bool, float, type(None))):\n # Primitive types can be passed through unmodified.\n output[attribute_name] = attribute\n elif isinstance(attribute, list):\n # Recursively deal with items in lists.\n output[attribute_name] = [\n self.to_representation(item) for item in attribute\n ]\n elif isinstance(attribute, dict):\n # Recursively deal with items in dictionaries.\n output[attribute_name] = {\n str(key): self.to_representation(value)\n for key, value in attribute.items()\n }\n else:\n # Force anything else to its string representation.\n output[attribute_name] = str(attribute)\n\n\n\n\n\nSerializer fields\n\n\nReadOnly\n field classes.\nThe \nField\n and \n\n\nThere are some minor tweaks to the field base classes.\n\n\nPreviously we had these two base classes:\n\n\n\n\nField\n as the base class for read-only fields. A default implementation was included for serializing data.\n\n\nWritableField\n as the base class for read-write fields.\n\n\n\n\nWe now use the following:\n\n\n\n\nField\n is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.\n\n\nReadOnlyField\n is a concrete implementation for read-only fields that simply returns the attribute value without modification.\n\n\n\n\nallow_null\n, \ndefault\n arguments.\nThe \nrequired\n, \nallow_blank\n and \n\n\nREST framework now has more explicit and clear control over validating empty values for fields.\n\n\nPreviously the meaning of the \nrequired=False\n keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be \nNone\n or the empty string.\n\n\nWe now have a better separation, with separate \nrequired\n, \nallow_null\n and \nallow_blank\n arguments.\n\n\nThe following set of arguments are used to control validation of empty values:\n\n\n\n\nrequired=False\n: The value does not need to be present in the input, and will not be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\ndefault=\nvalue\n: The value does not need to be present in the input, and a default value will be passed to \n.create()\n or \n.update()\n if it is not seen.\n\n\nallow_null=True\n: \nNone\n is a valid input.\n\n\nallow_blank=True\n: \n''\n is valid input. For \nCharField\n and subclasses only.\n\n\n\n\nTypically you'll want to use \nrequired=False\n if the corresponding model field has a default value, and additionally set either \nallow_null=True\n or \nallow_blank=True\n if required.\n\n\nThe \ndefault\n argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the \nrequired\n argument when a default is specified, and doing so will result in an error.\n\n\nCoercing output types.\n\n\nThe previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an \nIntegerField\n would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior.\n\n\nRemoval of \n.validate()\n.\n\n\nThe \n.validate()\n method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override \nto_internal_value()\n.\n\n\nclass UppercaseCharField(serializers.CharField):\n def to_internal_value(self, data):\n value = super(UppercaseCharField, self).to_internal_value(data)\n if value != value.upper():\n raise serializers.ValidationError('The input should be uppercase only.')\n return value\n\n\n\nPreviously validation errors could be raised in either \n.to_native()\n or \n.validate()\n, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.\n\n\nThe \nListField\n class.\n\n\nThe \nListField\n class has now been added. This field validates list input. It takes a \nchild\n keyword argument which is used to specify the field used to validate each item in the list. For example:\n\n\nscores = ListField(child=IntegerField(min_value=0, max_value=100))\n\n\n\nYou can also use a declarative style to create new subclasses of \nListField\n, like this:\n\n\nclass ScoresField(ListField):\n child = IntegerField(min_value=0, max_value=100)\n\n\n\nWe can now use the \nScoresField\n class inside another serializer:\n\n\nscores = ScoresField()\n\n\n\nSee also the new \nListSerializer\n class, which validates input in the same way, but also includes the serializer interfaces of \n.is_valid()\n, \n.data\n, \n.save()\n and so on.\n\n\nThe \nChoiceField\n class may now accept a flat list.\n\n\nThe \nChoiceField\n class may now accept a list of choices in addition to the existing style of using a list of pairs of \n(name, display_value)\n. The following is now valid:\n\n\ncolor = ChoiceField(choices=['red', 'green', 'blue'])\n\n\n\nThe \nMultipleChoiceField\n class.\n\n\nThe \nMultipleChoiceField\n class has been added. This field acts like \nChoiceField\n, but returns a set, which may include none, one or many of the valid choices.\n\n\nChanges to the custom field API.\n\n\nThe \nfrom_native(self, value)\n and \nto_native(self, data)\n method names have been replaced with the more obviously named \nto_internal_value(self, data)\n and \nto_representation(self, value)\n.\n\n\nThe \nfield_from_native()\n and \nfield_to_native()\n methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...\n\n\ndef field_to_native(self, obj, field_name):\n \"\"\"A custom read-only field that returns the class name.\"\"\"\n return obj.__class__.__name__\n\n\n\nNow if you need to access the entire object you'll instead need to override one or both of the following:\n\n\n\n\nUse \nget_attribute\n to modify the attribute value passed to \nto_representation()\n.\n\n\nUse \nget_value\n to modify the data value passed \nto_internal_value()\n.\n\n\n\n\nFor example:\n\n\ndef get_attribute(self, obj):\n # Pass the entire object through to `to_representation()`,\n # instead of the standard attribute lookup.\n return obj\n\ndef to_representation(self, value):\n return value.__class__.__name__\n\n\n\nExplicit \nqueryset\n required on relational fields.\n\n\nPreviously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a \nModelSerializer\n.\n\n\nThis code \nwould be valid\n in \n2.4.3\n:\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n class Meta:\n model = Account\n\n\n\nHowever this code \nwould not be valid\n in \n3.0\n:\n\n\n# Missing `queryset`\nclass AccountSerializer(serializers.Serializer):\n organizations = serializers.SlugRelatedField(slug_field='name')\n\n def restore_object(self, attrs, instance=None):\n # ...\n\n\n\nThe queryset argument is now always required for writable relational fields.\nThis removes some magic and makes it easier and more obvious to move between implicit \nModelSerializer\n classes and explicit \nSerializer\n classes.\n\n\nclass AccountSerializer(serializers.ModelSerializer):\n organizations = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Organization.objects.all()\n )\n\n class Meta:\n model = Account\n\n\n\nThe \nqueryset\n argument is only ever required for writable fields, and is not required or valid for fields with \nread_only=True\n.\n\n\nOptional argument to \nSerializerMethodField\n.\n\n\nThe argument to \nSerializerMethodField\n is now optional, and defaults to \nget_\nfield_name\n. For example the following is valid:\n\n\nclass AccountSerializer(serializers.Serializer):\n # `method_name='get_billing_details'` by default.\n billing_details = serializers.SerializerMethodField()\n\n def get_billing_details(self, account):\n return calculate_billing(account)\n\n\n\nIn order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code \nwill raise an error\n:\n\n\nbilling_details = serializers.SerializerMethodField('get_billing_details')\n\n\n\nEnforcing consistent \nsource\n usage.\n\n\nI've see several codebases that unnecessarily include the \nsource\n argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that \nsource\n is usually not required.\n\n\nThe following usage will \nnow raise an error\n:\n\n\nemail = serializers.EmailField(source='email')\n\n\n\nUniqueTogetherValidator\n classes.\nThe \nUniqueValidator\n and \n\n\nREST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit \nSerializer\n class instead of using \nModelSerializer\n.\n\n\nThe \nUniqueValidator\n should be applied to a serializer field, and takes a single \nqueryset\n argument.\n\n\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nclass OrganizationSerializer(serializers.Serializer):\n url = serializers.HyperlinkedIdentityField(view_name='organization_detail')\n created = serializers.DateTimeField(read_only=True)\n name = serializers.CharField(\n max_length=100,\n validators=UniqueValidator(queryset=Organization.objects.all())\n )\n\n\n\nThe \nUniqueTogetherValidator\n should be applied to a serializer, and takes a \nqueryset\n argument and a \nfields\n argument which should be a list or tuple of field names.\n\n\nclass RaceResultSerializer(serializers.Serializer):\n category = serializers.ChoiceField(['5k', '10k'])\n position = serializers.IntegerField()\n name = serializers.CharField(max_length=100)\n\n class Meta:\n validators = [UniqueTogetherValidator(\n queryset=RaceResult.objects.all(),\n fields=('category', 'position')\n )]\n\n\n\nThe \nUniqueForDateValidator\n classes.\n\n\nREST framework also now includes explicit validator classes for validating the \nunique_for_date\n, \nunique_for_month\n, and \nunique_for_year\n model field constraints. These are used internally instead of calling into \nModel.full_clean()\n.\n\n\nThese classes are documented in the \nValidators\n section of the documentation.\n\n\n\n\nGeneric views\n\n\nSimplification of view logic.\n\n\nThe view logic for the default method handlers has been significantly simplified, due to the new serializers API.\n\n\nChanges to pre/post save hooks.\n\n\nThe \npre_save\n and \npost_save\n hooks no longer exist, but are replaced with \nperform_create(self, serializer)\n and \nperform_update(self, serializer)\n.\n\n\nThese methods should save the object instance by calling \nserializer.save()\n, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.\n\n\nFor example:\n\n\ndef perform_create(self, serializer):\n # Include the owner attribute directly, rather than from request data.\n instance = serializer.save(owner=self.request.user)\n # Perform a custom post-save action.\n send_email(instance.to_email, instance.message)\n\n\n\nThe \npre_delete\n and \npost_delete\n hooks no longer exist, and are replaced with \n.perform_destroy(self, instance)\n, which should delete the instance and perform any custom actions.\n\n\ndef perform_destroy(self, instance):\n # Perform a custom pre-delete action.\n send_deletion_alert(user=instance.created_by, deleted=instance)\n # Delete the object instance.\n instance.delete()\n\n\n\nRemoval of view attributes.\n\n\nThe \n.object\n and \n.object_list\n attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.\n\n\nI would personally recommend that developers treat view instances as immutable objects in their application code.\n\n\nPUT as create.\n\n\nAllowing \nPUT\n as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning \n404\n responses.\n\n\nBoth styles \"\nPUT\n as 404\" and \"\nPUT\n as create\" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.\n\n\nIf you need to restore the previous behavior you may want to include \nthis \nAllowPUTAsCreateMixin\n class\n as a mixin to your views.\n\n\nCustomizing error responses.\n\n\nThe generic views now raise \nValidationFailed\n exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a \n400 Bad Request\n response directly.\n\n\nThis change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.\n\n\n\n\nThe metadata API\n\n\nBehavior for dealing with \nOPTIONS\n requests was previously built directly into the class-based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.\n\n\nThis makes it far easier to use a different style for \nOPTIONS\n responses throughout your API, and makes it possible to create third-party metadata policies.\n\n\n\n\nSerializers as HTML forms\n\n\nREST framework 3.0 includes templated HTML form rendering for serializers.\n\n\nThis API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.\n\n\nSignificant changes that you do need to be aware of include:\n\n\n\n\nNested HTML forms are now supported, for example, a \nUserSerializer\n with a nested \nProfileSerializer\n will now render a nested \nfieldset\n when used in the browsable API.\n\n\nNested lists of HTML forms are not yet supported, but are planned for 3.1.\n\n\nBecause we now use templated HTML form generation, \nthe \nwidget\n option is no longer available for serializer fields\n. You can instead control the template that is used for a given field, by using the \nstyle\n dictionary.\n\n\n\n\nThe \nstyle\n keyword argument for serializer fields.\n\n\nThe \nstyle\n keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the \nHTMLFormRenderer\n uses the \nbase_template\n key to determine which template to render the field with.\n\n\nFor example, to use a \ntextarea\n control instead of the default \ninput\n control, you would use the following\u2026\n\n\nadditional_notes = serializers.CharField(\n style={'base_template': 'textarea.html'}\n)\n\n\n\nSimilarly, to use a radio button control instead of the default \nselect\n control, you would use the following\u2026\n\n\ncolor_channel = serializers.ChoiceField(\n choices=['red', 'blue', 'green'],\n style={'base_template': 'radio.html'}\n)\n\n\n\nThis API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.\n\n\n\n\nAPI style\n\n\nThere are some improvements in the default style we use in our API responses.\n\n\nUnicode JSON by default.\n\n\nUnicode JSON is now the default. The \nUnicodeJSONRenderer\n class no longer exists, and the \nUNICODE_JSON\n setting has been added. To revert this behavior use the new setting:\n\n\nREST_FRAMEWORK = {\n 'UNICODE_JSON': False\n}\n\n\n\nCompact JSON by default.\n\n\nWe now output compact JSON in responses by default. For example, we return:\n\n\n{\"email\":\"amy@example.com\",\"is_admin\":true}\n\n\n\nInstead of the following:\n\n\n{\"email\": \"amy@example.com\", \"is_admin\": true}\n\n\n\nThe \nCOMPACT_JSON\n setting has been added, and can be used to revert this behavior if needed:\n\n\nREST_FRAMEWORK = {\n 'COMPACT_JSON': False\n}\n\n\n\nFile fields as URLs\n\n\nThe \nFileField\n and \nImageField\n classes are now represented as URLs by default. You should ensure you set Django's \nstandard \nMEDIA_URL\n setting\n appropriately, and ensure your application \nserves the uploaded files\n.\n\n\nYou can revert this behavior, and display filenames in the representation by using the \nUPLOADED_FILES_USE_URL\n settings key:\n\n\nREST_FRAMEWORK = {\n 'UPLOADED_FILES_USE_URL': False\n}\n\n\n\nYou can also modify serializer fields individually, using the \nuse_url\n argument:\n\n\nuploaded_file = serializers.FileField(use_url=False)\n\n\n\nAlso note that you should pass the \nrequest\n object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form \nhttps://example.com/url_path/filename.txt\n. For example:\n\n\ncontext = {'request': request}\nserializer = ExampleSerializer(instance, context=context)\nreturn Response(serializer.data)\n\n\n\nIf the request is omitted from the context, the returned URLs will be of the form \n/url_path/filename.txt\n.\n\n\nThrottle headers using \nRetry-After\n.\n\n\nThe custom \nX-Throttle-Wait-Second\n header has now been dropped in favor of the standard \nRetry-After\n header. You can revert this behavior if needed by writing a custom exception handler for your application.\n\n\nDate and time objects as ISO-8601 strings in serializer data.\n\n\nDate and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as \nDate\n, \nTime\n and \nDateTime\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by settings the existing \nDATE_FORMAT\n, \nDATETIME_FORMAT\n and \nTIME_FORMAT\n settings keys. Setting these values to \nNone\n instead of their default value of \n'iso-8601'\n will result in native objects being returned in serializer data.\n\n\nREST_FRAMEWORK = {\n # Return native `Date` and `Time` objects in `serializer.data`\n 'DATETIME_FORMAT': None\n 'DATE_FORMAT': None\n 'TIME_FORMAT': None\n}\n\n\n\nYou can also modify serializer fields individually, using the \ndate_format\n, \ntime_format\n and \ndatetime_format\n arguments:\n\n\n# Return `DateTime` instances in `serializer.data`, not strings.\ncreated = serializers.DateTimeField(format=None)\n\n\n\nDecimals as strings in serializer data.\n\n\nDecimals are now coerced to strings by default in the serializer output. Previously they were returned as \nDecimal\n objects, and later coerced to strings by the renderer.\n\n\nYou can modify this behavior globally by using the \nCOERCE_DECIMAL_TO_STRING\n settings key.\n\n\nREST_FRAMEWORK = {\n 'COERCE_DECIMAL_TO_STRING': False\n}\n\n\n\nOr modify it on an individual serializer field, using the \ncoerce_to_string\n keyword argument.\n\n\n# Return `Decimal` instances in `serializer.data`, not strings.\namount = serializers.DecimalField(\n max_digits=10,\n decimal_places=2,\n coerce_to_string=False\n)\n\n\n\nThe default JSON renderer will return float objects for un-coerced \nDecimal\n instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.\n\n\n\n\nMiscellaneous notes\n\n\n\n\nThe serializer \nChoiceField\n does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.\n\n\nDue to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party \"autocomplete\" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.\n\n\nSome of the default validation error messages were rewritten and might no longer be pre-translated. You can still \ncreate language files with Django\n if you wish to localize them.\n\n\nAPIException\n subclasses could previously take any arbitrary type in the \ndetail\n argument. These exceptions now use translatable text strings, and as a result call \nforce_text\n on the \ndetail\n argument, which \nmust be a string\n. If you need complex arguments to an \nAPIException\n class, you should subclass it and override the \n__init__()\n method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.\n\n\n\n\n\n\nWhat's coming next\n\n\n3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.\n\n\nThe 3.1 release is planned to address improvements in the following components:\n\n\n\n\nPublic API for using serializers as HTML forms.\n\n\nRequest parsing, mediatypes \n the implementation of the browsable API.\n\n\nIntroduction of a new pagination API.\n\n\nBetter support for API versioning.\n\n\n\n\nThe 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.\n\n\nYou can follow development on the GitHub site, where we use \nmilestones to indicate planning timescales\n.", @@ -5210,6 +5300,61 @@ "text": "ModelSerializer and HyperlinkedModelSerializer must include either a fields\noption, or an exclude option. The fields = '__all__' shortcut may be used to\nexplicitly include all fields. Failing to set either fields or exclude raised a pending deprecation warning\nin version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.", "title": "ModelSerializer 'fields' and 'exclude'" }, + { + "location": "/topics/3.6-announcement/", + "text": ".promo li a {\n float: left;\n width: 130px;\n height: 20px;\n text-align: center;\n margin: 10px 30px;\n padding: 150px 0 0 0;\n background-position: 0 50%;\n background-size: 130px auto;\n background-repeat: no-repeat;\n font-size: 120%;\n color: black;\n}\n.promo li {\n list-style: none;\n}\n\n\n\n\nDjango REST framework 3.6\n\n\nThe 3.6 release adds two major new features to REST framework.\n\n\n\n\nBuilt-in interactive API documentation support.\n\n\nA new JavaScript client\nlibrary.\n\n\n\n\n\n\nAbove: The interactive API documentation.\n\n\n\n\nFunding\n\n\nThe 3.6 release would not have been possible without our \nbacking from Mozilla\n to the project, and our \ncollaborative funding\nmodel\n.\n\n\nIf you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by\n\nsigning up for a paid\nplan\n.\n\n\n\n \nRover.com\n\n \nSentry\n\n \nStream\n\n \nMachinalis\n\n \nRollbar\n\n \nMicroPyramid\n\n\n\n\n\n\n\n\nMany thanks to all our \nsponsors\n, and in particular to our premium backers, \nRover\n, \nSentry\n, \nStream\n, \nMachinalis\n, \nRollbar\n, and \nMicroPyramid\n.\n\n\n\n\nInteractive API documentation\n\n\nREST framework's new API documentation supports a number of features:\n\n\n\n\nLive API interaction.\n\n\nSupport for various authentication schemes.\n\n\nCode snippets for the Python, JavaScript, and Command Line clients.\n\n\n\n\nThe \ncoreapi\n library is required as a dependancy for the API docs. Make sure\nto install the latest version (2.3.0 or above). The \npygments\n and \nmarkdown\n\nlibraries are optional but recommended.\n\n\nTo install the API documentation, you'll need to include it in your projects URLconf:\n\n\nfrom rest_framework.documentation import include_docs_urls\n\nAPI_TITLE = 'API title'\nAPI_DESCRIPTION = '...'\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))\n]\n\n\n\nOnce installed you should see something a little like this:\n\n\n\n\nWe'll likely be making further refinements to the API documentation over the\ncoming weeks. Keep in mind that this is a new feature, and please do give\nus feedback if you run into any issues or limitations.\n\n\nFor more information on documenting your API endpoints see the \n\"Documenting your API\"\n section.\n\n\n\n\nJavaScript client library\n\n\nThe JavaScript client library allows you to load an API schema, and then interact\nwith that API at an application layer interface, rather than constructing fetch\nrequests explicitly.\n\n\nHere's a brief example that demonstrates:\n\n\n\n\nLoading the client library and schema.\n\n\nInstantiating an authenticated client.\n\n\nMaking an API request using the client.\n\n\n\n\nindex.html\n\n\nhtml\n\n \nhead\n\n \nscript src=\"/static/rest_framework/js/coreapi-0.1.0.js\"\n/script\n\n \nscript src=\"/docs/schema.js' %}\"\n/script\n\n \nscript\n\n const coreapi = window.coreapi\n const schema = window.schema\n\n // Instantiate a client...\n let auth = coreapi.auth.TokenAuthentication({scheme: 'JWT', token: 'xxx'})\n let client = coreapi.Client({auth: auth})\n\n // Make an API request...\n client.action(schema, ['projects', 'list']).then(function(result) {\n alert(result)\n })\n \n/script\n\n \n/head\n\n\n/html\n\n\n\n\nThe JavaScript client library supports various authentication schemes, and can be\nused by your project itself, or as an external client interacting with your API.\n\n\nThe client is not limited to usage with REST framework APIs, although it does\ncurrently only support loading CoreJSON API schemas. Support for Swagger and\nother API schemas is planned.\n\n\nFor more details see the \nJavaScript client library documentation\n.\n\n\nAuthentication classes for the Python client library\n\n\nPrevious authentication support in the Python client library was limited to\nallowing users to provide explicit header values.\n\n\nWe now have better support for handling the details of authentication, with\nthe introduction of the \nBasicAuthentication\n, \nTokenAuthentication\n, and\n\nSessionAuthentication\n schemes.\n\n\nYou can include the authentication scheme when instantiating a new client.\n\n\nauth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')\nclient = coreapi.Client(auth=auth)\n\n\n\nFor more information see the \nPython client library documentation\n.\n\n\n\n\nDeprecations\n\n\nUpdating \ncoreapi\n\n\nIf you're using REST framework's schema generation, or want to use the API docs,\nthen you'll need to update to the latest version of coreapi. (2.3.0)\n\n\nGenerating schemas from Router\n\n\nThe 3.5 \"pending deprecation\" of router arguments for generating a schema view, such as \nschema_title\n, \nschema_url\n and \nschema_renderers\n, have now been escalated to a\n\"deprecated\" warning.\n\n\nInstead of using \nDefaultRouter(schema_title='Example API')\n, you should use the \nget_schema_view()\n function, and include the view explicitly in your URL conf.\n\n\nDjangoFilterBackend\n\n\nThe 3.5 \"pending deprecation\" warning of the built-in \nDjangoFilterBackend\n has now\nbeen escalated to a \"deprecated\" warning.\n\n\nYou should change your imports and REST framework filter settings as follows:\n\n\n\n\nrest_framework.filters.DjangoFilterBackend\n becomes \ndjango_filters.rest_framework.DjangoFilterBackend\n.\n\n\nrest_framework.filters.FilterSet\n becomes \ndjango_filters.rest_framework.FilterSet\n.\n\n\n\n\n\n\nWhat's next\n\n\nThere are likely to be a number of refinements to the API documentation and\nJavaScript client library over the coming weeks, which could include some of the following:\n\n\n\n\nSupport for private API docs, requiring login.\n\n\nFile upload and download support in the JavaScript client \n API docs.\n\n\nComprehensive documentation for the JavaScript client library.\n\n\nAutomatically including authentication details in the API doc code snippets.\n\n\nAdding authentication support in the command line client.\n\n\nSupport for loading Swagger and other schemas in the JavaScript client.\n\n\nImproved support for documenting parameter schemas and response schemas.\n\n\nRefining the API documentation interaction modal.\n\n\n\n\nOnce work on those refinements is complete, we'll be starting feature work\non realtime support, for the 3.7 release.", + "title": "3.6 Announcement" + }, + { + "location": "/topics/3.6-announcement/#django-rest-framework-36", + "text": "The 3.6 release adds two major new features to REST framework. Built-in interactive API documentation support. A new JavaScript client library. Above: The interactive API documentation.", + "title": "Django REST framework 3.6" + }, + { + "location": "/topics/3.6-announcement/#funding", + "text": "The 3.6 release would not have been possible without our backing from Mozilla to the project, and our collaborative funding model . If you use REST framework commercially and would like to see this work continue,\nwe strongly encourage you to invest in its continued development by signing up for a paid plan . \n Rover.com \n Sentry \n Stream \n Machinalis \n Rollbar \n MicroPyramid Many thanks to all our sponsors , and in particular to our premium backers, Rover , Sentry , Stream , Machinalis , Rollbar , and MicroPyramid .", + "title": "Funding" + }, + { + "location": "/topics/3.6-announcement/#interactive-api-documentation", + "text": "REST framework's new API documentation supports a number of features: Live API interaction. Support for various authentication schemes. Code snippets for the Python, JavaScript, and Command Line clients. The coreapi library is required as a dependancy for the API docs. Make sure\nto install the latest version (2.3.0 or above). The pygments and markdown \nlibraries are optional but recommended. To install the API documentation, you'll need to include it in your projects URLconf: from rest_framework.documentation import include_docs_urls\n\nAPI_TITLE = 'API title'\nAPI_DESCRIPTION = '...'\n\nurlpatterns = [\n ...\n url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION))\n] Once installed you should see something a little like this: We'll likely be making further refinements to the API documentation over the\ncoming weeks. Keep in mind that this is a new feature, and please do give\nus feedback if you run into any issues or limitations. For more information on documenting your API endpoints see the \"Documenting your API\" section.", + "title": "Interactive API documentation" + }, + { + "location": "/topics/3.6-announcement/#javascript-client-library", + "text": "The JavaScript client library allows you to load an API schema, and then interact\nwith that API at an application layer interface, rather than constructing fetch\nrequests explicitly. Here's a brief example that demonstrates: Loading the client library and schema. Instantiating an authenticated client. Making an API request using the client. index.html html \n head \n script src=\"/static/rest_framework/js/coreapi-0.1.0.js\" /script \n script src=\"/docs/schema.js' %}\" /script \n script \n const coreapi = window.coreapi\n const schema = window.schema\n\n // Instantiate a client...\n let auth = coreapi.auth.TokenAuthentication({scheme: 'JWT', token: 'xxx'})\n let client = coreapi.Client({auth: auth})\n\n // Make an API request...\n client.action(schema, ['projects', 'list']).then(function(result) {\n alert(result)\n })\n /script \n /head /html The JavaScript client library supports various authentication schemes, and can be\nused by your project itself, or as an external client interacting with your API. The client is not limited to usage with REST framework APIs, although it does\ncurrently only support loading CoreJSON API schemas. Support for Swagger and\nother API schemas is planned. For more details see the JavaScript client library documentation .", + "title": "JavaScript client library" + }, + { + "location": "/topics/3.6-announcement/#authentication-classes-for-the-python-client-library", + "text": "Previous authentication support in the Python client library was limited to\nallowing users to provide explicit header values. We now have better support for handling the details of authentication, with\nthe introduction of the BasicAuthentication , TokenAuthentication , and SessionAuthentication schemes. You can include the authentication scheme when instantiating a new client. auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx')\nclient = coreapi.Client(auth=auth) For more information see the Python client library documentation .", + "title": "Authentication classes for the Python client library" + }, + { + "location": "/topics/3.6-announcement/#deprecations", + "text": "", + "title": "Deprecations" + }, + { + "location": "/topics/3.6-announcement/#updating-coreapi", + "text": "If you're using REST framework's schema generation, or want to use the API docs,\nthen you'll need to update to the latest version of coreapi. (2.3.0)", + "title": "Updating coreapi" + }, + { + "location": "/topics/3.6-announcement/#generating-schemas-from-router", + "text": "The 3.5 \"pending deprecation\" of router arguments for generating a schema view, such as schema_title , schema_url and schema_renderers , have now been escalated to a\n\"deprecated\" warning. Instead of using DefaultRouter(schema_title='Example API') , you should use the get_schema_view() function, and include the view explicitly in your URL conf.", + "title": "Generating schemas from Router" + }, + { + "location": "/topics/3.6-announcement/#djangofilterbackend", + "text": "The 3.5 \"pending deprecation\" warning of the built-in DjangoFilterBackend has now\nbeen escalated to a \"deprecated\" warning. You should change your imports and REST framework filter settings as follows: rest_framework.filters.DjangoFilterBackend becomes django_filters.rest_framework.DjangoFilterBackend . rest_framework.filters.FilterSet becomes django_filters.rest_framework.FilterSet .", + "title": "DjangoFilterBackend" + }, + { + "location": "/topics/3.6-announcement/#whats-next", + "text": "There are likely to be a number of refinements to the API documentation and\nJavaScript client library over the coming weeks, which could include some of the following: Support for private API docs, requiring login. File upload and download support in the JavaScript client API docs. Comprehensive documentation for the JavaScript client library. Automatically including authentication details in the API doc code snippets. Adding authentication support in the command line client. Support for loading Swagger and other schemas in the JavaScript client. Improved support for documenting parameter schemas and response schemas. Refining the API documentation interaction modal. Once work on those refinements is complete, we'll be starting feature work\non realtime support, for the 3.7 release.", + "title": "What's next" + }, { "location": "/topics/kickstarter-announcement/", "text": "Kickstarting Django REST framework 3\n\n\n\n\n \n\n\n\n\n\nIn order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3.\n\n\nProject details\n\n\nThis new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following:\n\n\n\n\nFaster, simpler and easier-to-use serializers.\n\n\nAn alternative admin-style interface for the browsable API.\n\n\nSearch and filtering controls made accessible in the browsable API.\n\n\nAlternative API pagination styles.\n\n\nDocumentation around API versioning.\n\n\nTriage of outstanding tickets.\n\n\nImproving the ongoing quality and maintainability of the project.\n\n\n\n\nFull details are available now on the \nproject page\n.\n\n\nIf you're interested in helping make sustainable open source development a reality please \nvisit the Kickstarter page\n and consider funding the project.\n\n\nI can't wait to see where this takes us!\n\n\nMany thanks to everyone for your support so far,\n\n\nTom Christie :)\n\n\n\n\nSponsors\n\n\nWe've now blazed way past all our goals, with a staggering \u00a330,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible.\n\n\n\n\nPlatinum sponsors\n\n\nOur platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.\n\n\n\n\nEventbrite\n\n\n\n\n\n\n\nDivio\n\n\nLulu\n\n\nPotato\n\n\nWiredrive\n\n\nCyan\n\n\nRunscope\n\n\nSimple Energy\n\n\nVOKAL Interactive\n\n\nPurple Bit\n\n\nKuwaitNET\n\n\n\n\n\n\n\n\n\n\nGold sponsors\n\n\nOur gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.\n\n\n\n\nLaterPay\n\n\nSchuberg Philis\n\n\nProReNata AB\n\n\nSGA Websites\n\n\nSirono\n\n\nVinta Software Studio\n\n\nRapasso\n\n\nMirus Research\n\n\nHipo\n\n\nByte\n\n\nLightning Kite\n\n\nOpbeat\n\n\nKoordinates\n\n\nPulsecode Inc.\n\n\nSinging Horse Studio Ltd.\n\n\nHeroku\n\n\nRheinwerk Verlag\n\n\nSecurity Compass\n\n\nDjango Software Foundation\n\n\nHipflask\n\n\nCrate\n\n\nCryptico Corp\n\n\nNextHub\n\n\nCompile\n\n\nWusaWork\n\n\nEnvision Linux\n\n\n\n\n\n\n\n\n\n\nSilver sponsors\n\n\nThe serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank\nyou to individuals who have chosen to privately support the project at this level.\n\n\n\n\nIMT Computer Services\n\n\nWildfish\n\n\nThermondo GmbH\n\n\nProvidenz\n\n\nalwaysdata.com\n\n\nTriggered Messaging\n\n\nPushPull Technology Ltd\n\n\nTranscode\n\n\nGarfo\n\n\nShippo\n\n\nGizmag\n\n\nTivix\n\n\nSafari\n\n\nBright Loop\n\n\nABA Systems\n\n\nbeefarm.ru\n\n\nVzzual.com\n\n\nInfinite Code\n\n\nCrossword Tracker\n\n\nPkgFarm\n\n\nLife. The Game.\n\n\nBlimp\n\n\nPathwright\n\n\nFluxility\n\n\nTeonite\n\n\nTrackMaven\n\n\nPhurba\n\n\nNephila\n\n\nAditium\n\n\nOpenEye Scientific Software\n\n\nHolvi\n\n\nCantemo\n\n\nMakeSpace\n\n\nAX Semantics\n\n\nISL\n\n\n\n\n\n\n\n\nIndividual backers\n: Paul Hallett, \nPaul Whipp\n, Dylan Roy, Jannis Leidel, \nXavier Ordoquy\n, \nJohannes Spielmann\n, \nRob Spectre\n, \nChris Heisel\n, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen.\n\n\n\n\nAdvocates\n\n\nThe following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you!\n\n\nIndividual backers\n: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, D\u00e9c\u00e9bal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkk\u00e4, Charalampos Papaloizou, Nikolai R\u00f8ed Kristiansen, Antoni Aloy L\u00f3pez, Celia Oakley, Micha\u0142 Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel.\n\n\nCorporate backers\n: Savannah Informatics, Prism Skylabs, Musical Operating Devices.\n\n\n\n\nSupporters\n\n\nThere were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!", @@ -5534,21 +5679,6 @@ "location": "/topics/release-notes/#300", "text": "Date : 1st December 2014 For full details see the 3.0 release announcement . For older release notes, please see the version 2.x documentation .", "title": "3.0.0" - }, - { - "location": "/topics/jobs/", - "text": "Jobs\n\n\nLooking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of \nour sponsors are hiring\n.\n\n\nPlaces to Look for Django REST Framework Jobs\n\n\n\n\nhttps://www.djangoproject.com/community/jobs/\n\n\nhttps://www.python.org/jobs/\n\n\nhttps://djangogigs.com\n\n\nhttps://djangojobs.net/jobs/\n\n\nhttp://djangojobbers.com\n\n\nhttps://www.indeed.com/q-Django-jobs.html\n\n\nhttp://stackoverflow.com/jobs/developer-jobs-using-django\n\n\nhttps://www.upwork.com/o/jobs/browse/skill/django-framework/\n\n\nhttps://www.technojobs.co.uk/django-jobs\n\n\nhttps://remoteok.io/remote-django-jobs\n\n\nhttps://www.remotepython.com/jobs/\n\n\n\n\nKnow of any other great resources for Django REST Framework jobs that are missing in our list? Please \nsubmit a pull request\n or \nemail us\n.\n\n\nWonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for \nREST Framework sponsorship\n yet.", - "title": "Jobs" - }, - { - "location": "/topics/jobs/#jobs", - "text": "Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of our sponsors are hiring .", - "title": "Jobs" - }, - { - "location": "/topics/jobs/#places-to-look-for-django-rest-framework-jobs", - "text": "https://www.djangoproject.com/community/jobs/ https://www.python.org/jobs/ https://djangogigs.com https://djangojobs.net/jobs/ http://djangojobbers.com https://www.indeed.com/q-Django-jobs.html http://stackoverflow.com/jobs/developer-jobs-using-django https://www.upwork.com/o/jobs/browse/skill/django-framework/ https://www.technojobs.co.uk/django-jobs https://remoteok.io/remote-django-jobs https://www.remotepython.com/jobs/ Know of any other great resources for Django REST Framework jobs that are missing in our list? Please submit a pull request or email us . Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for REST Framework sponsorship yet.", - "title": "Places to Look for Django REST Framework Jobs" } ] } \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 5baa526eb..d9f6e419f 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -4,7 +4,7 @@ http://www.django-rest-framework.org// - 2017-02-27 + 2017-03-09 daily @@ -13,49 +13,49 @@ http://www.django-rest-framework.org//tutorial/quickstart/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//tutorial/1-serialization/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//tutorial/2-requests-and-responses/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//tutorial/3-class-based-views/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//tutorial/4-authentication-and-permissions/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//tutorial/5-relationships-and-hyperlinked-apis/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//tutorial/6-viewsets-and-routers/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//tutorial/7-schemas-and-client-libraries/ - 2017-02-27 + 2017-03-09 daily @@ -65,163 +65,163 @@ http://www.django-rest-framework.org//api-guide/requests/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/responses/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/views/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/generic-views/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/viewsets/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/routers/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/parsers/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/renderers/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/serializers/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/fields/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/relations/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/validators/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/authentication/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/permissions/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/throttling/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/filtering/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/pagination/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/versioning/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/content-negotiation/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/metadata/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/schemas/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/format-suffixes/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/reverse/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/exceptions/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/status-codes/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/testing/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//api-guide/settings/ - 2017-02-27 + 2017-03-09 daily @@ -231,139 +231,145 @@ http://www.django-rest-framework.org//topics/documenting-your-api/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/api-clients/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/internationalization/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/ajax-csrf-cors/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/html-and-forms/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/browser-enhancements/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/browsable-api/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/rest-hypermedia-hateoas/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/third-party-packages/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/tutorials-and-resources/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/contributing/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/project-management/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/3.0-announcement/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/3.1-announcement/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/3.2-announcement/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/3.3-announcement/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/3.4-announcement/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/3.5-announcement/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/kickstarter-announcement/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/mozilla-grant/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/funding/ - 2017-02-27 - daily - - - - http://www.django-rest-framework.org//topics/release-notes/ - 2017-02-27 + 2017-03-09 daily http://www.django-rest-framework.org//topics/jobs/ - 2017-02-27 + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/3.0-announcement/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/3.1-announcement/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/3.2-announcement/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/3.3-announcement/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/3.4-announcement/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/3.5-announcement/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/3.6-announcement/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/kickstarter-announcement/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/mozilla-grant/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/funding/ + 2017-03-09 + daily + + + + http://www.django-rest-framework.org//topics/release-notes/ + 2017-03-09 daily diff --git a/topics/3.0-announcement/index.html b/topics/3.0-announcement/index.html index 3333dfd42..b791e36ee 100644 --- a/topics/3.0-announcement/index.html +++ b/topics/3.0-announcement/index.html @@ -61,7 +61,7 @@ - Search @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/topics/3.1-announcement/index.html b/topics/3.1-announcement/index.html index 645570595..1bfac0547 100644 --- a/topics/3.1-announcement/index.html +++ b/topics/3.1-announcement/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/topics/3.2-announcement/index.html b/topics/3.2-announcement/index.html index 7dfc32c5a..cfb9b18f9 100644 --- a/topics/3.2-announcement/index.html +++ b/topics/3.2-announcement/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/topics/3.3-announcement/index.html b/topics/3.3-announcement/index.html index fc0df5c0c..41aa3a967 100644 --- a/topics/3.3-announcement/index.html +++ b/topics/3.3-announcement/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/topics/3.4-announcement/index.html b/topics/3.4-announcement/index.html index c1b5de185..d4b0e76bb 100644 --- a/topics/3.4-announcement/index.html +++ b/topics/3.4-announcement/index.html @@ -286,6 +286,10 @@ Project management +
  • + Jobs +
  • +
  • 3.0 Announcement
  • @@ -310,6 +314,10 @@ 3.5 Announcement +
  • + 3.6 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -326,10 +334,6 @@ Release Notes -
  • - Jobs -
  • - diff --git a/topics/3.5-announcement/index.html b/topics/3.5-announcement/index.html index 18bb864e2..fafc47a8c 100644 --- a/topics/3.5-announcement/index.html +++ b/topics/3.5-announcement/index.html @@ -58,7 +58,7 @@