diff --git a/404.html b/404.html index 38b436a53..484d2b2c0 100644 --- a/404.html +++ b/404.html @@ -4,18 +4,18 @@ - Django REST framework - 404 - Page not found - - + Django REST framework + + - + - - - - + + + + + - + +
+ - + ================================================== --> - - - + + + + + + + - +
+
+ +
+
+
- - - - authentication.py - - + -

Authentication

+ + + + authentication.py + + + + +

Authentication

Auth needs to be pluggable.

— Jacob Kaplan-Moss, "REST worst practices"

-

Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted.

+

Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted.

REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.

Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.

The request.user property will typically be set to an instance of the contrib.auth package's User class.

The request.auth property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.


Note: Don't forget that authentication by itself won't allow or disallow an incoming request, it simply identifies the credentials that the request was made with.

-

For information on how to setup the permission polices for your API please see the permissions documentation.

+

For information on how to setup the permission polices for your API please see the permissions documentation.


How authentication is determined

The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set request.user and request.auth using the return value of the first class that successfully authenticates.

@@ -640,6 +638,8 @@ python manage.py createsuperuser

Unauthenticated responses that are denied permission will result in an HTTP 403 Forbidden response.

If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as PUT, PATCH, POST or DELETE requests. See the Django CSRF documentation for more details.

+

Warning: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.

+

CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.

Custom authentication

To implement a custom authentication scheme, subclass BaseAuthentication and override the .authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.

In some circumstances instead of returning None, you may want to raise an AuthenticationFailed exception from the .authenticate() method.

@@ -714,6 +714,8 @@ REST_FRAMEWORK = {

django-rest-auth

Django-rest-auth library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.

+ +
@@ -737,6 +739,8 @@ REST_FRAMEWORK = { + + - +
+
+ +
+
+
- - - - negotiation.py - - + -

Content negotiation

+ + + + negotiation.py + + + + +

Content negotiation

HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.

RFC 2616, Fielding et al.

@@ -461,6 +459,8 @@ class NoNegotiationView(APIView): }) + +
@@ -484,6 +484,8 @@ class NoNegotiationView(APIView): + + - +
+
+ +
+
+
- - - - exceptions.py - - + -

Exceptions

+ + + + exceptions.py + + + + +

Exceptions

Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.

— Doug Hellmann, Python Exception Handling Techniques

@@ -518,11 +516,11 @@ class ServiceUnavailable(APIException):

AuthenticationFailed

Signature: AuthenticationFailed(detail=None)

Raised when an incoming request includes incorrect authentication.

-

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.

+

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.

NotAuthenticated

Signature: NotAuthenticated(detail=None)

Raised when an unauthenticated request fails the permission checks.

-

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.

+

By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the authentication documentation for more details.

PermissionDenied

Signature: PermissionDenied(detail=None)

Raised when an authenticated request fails the permission checks.

@@ -561,6 +559,8 @@ class ServiceUnavailable(APIException):

The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.

By default this exception results in a response with the HTTP status code "400 Bad Request".

+ +
@@ -584,6 +584,8 @@ class ServiceUnavailable(APIException): + + - +
+
+ +
+
+
- - - - fields.py - - + -

Serializer fields

+ + + + fields.py + + + + +

Serializer fields

Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.

Django documentation

@@ -680,6 +686,25 @@ color_channel = serializers.ChoiceField(

A field that ensures the input is a valid UUID string. The to_internal_value method will return a uuid.UUID instance. On output the field will return a string in the canonical hyphenated format, for example:

"de305d54-75b4-431b-adb2-eb6b9e546013"
 
+

Signature: UUIDField(format='hex_verbose')

+ +

IPAddressField

+

A field that ensures the input is a valid IPv4 or IPv6 string.

+

Corresponds to django.forms.fields.IPAddressField and django.forms.fields.GenericIPAddressField.

+

Signature: IPAddressField(protocol='both', unpack_ipv4=False, **options)

+

Numeric fields

IntegerField

@@ -761,6 +786,13 @@ color_channel = serializers.ChoiceField(

TimeField format strings

Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000')

+

DurationField

+

A Duration representation. +Corresponds to django.db.models.fields.DurationField

+

The validated_data for these fields will contain a datetime.timedelta instance. +The representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]'.

+

Note: This field is only available with Django versions >= 1.8.

+

Signature: DurationField()


Choice selection fields

ChoiceField

@@ -854,7 +886,7 @@ Django's regular validators documentation.

+

For further examples on HiddenField see the validators documentation.

ModelField

A generic field that can be tied to any arbitrary model field. The ModelField 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.

This field is used by ModelSerializer to correspond to custom model field classes.

@@ -979,6 +1011,8 @@ def to_internal_value(self, data):

django-rest-framework-hstore

The django-rest-framework-hstore package provides an HStoreField to support django-hstore DictionaryField model field.

+ +
@@ -1002,6 +1036,8 @@ def to_internal_value(self, data): + + - +
+
+ +
+
+
- - - - filters.py - - + -

Filtering

+ + + + filters.py + + + + +

Filtering

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.

Django documentation

@@ -758,6 +756,8 @@ class ProductFilter(django_filters.FilterSet):

Django REST framework full word search filter

The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match.

+ +
@@ -781,6 +781,8 @@ class ProductFilter(django_filters.FilterSet): + + - +
+
+ +
+
+
- - - - urlpatterns.py - - + -

Format suffixes

+ + + + urlpatterns.py + + + + +

Format suffixes

Section 6.2.1 does not say that content negotiation should be used all the time.

@@ -437,6 +435,8 @@ urlpatterns = i18n_patterns(

“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, REST discuss mailing list

The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.

+ +
@@ -460,6 +460,8 @@ urlpatterns = i18n_patterns( + + - +
+
+ +
+
+
- - - - mixins.py - - - - generics.py - - + -

Generic views

+ + + + mixins.py + + + + generics.py + + + + +

Generic views

Django’s 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.

Django Documentation

@@ -757,6 +755,8 @@ class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,

Django REST Framework bulk

The django-rest-framework-bulk package implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.

+ +
@@ -780,6 +780,8 @@ class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin, + + - +
+
+ +
+
+
- - - - metadata.py - - + -

Metadata

+ + + + metadata.py + + + + +

Metadata

[The OPTIONS] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

RFC7231, Section 4.3.7.

@@ -469,6 +467,8 @@ def schema(self, request): } + +
@@ -492,6 +492,8 @@ def schema(self, request): + + - +
+
+ +
+
+
- - - - pagination.py - - + -

Pagination

+ + + + pagination.py + + + + +

Pagination

Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.

Django documentation

@@ -652,7 +650,7 @@ class StandardResultsSetPagination(PageNumberPagination):

API responses for list endpoints will now include a Link header, instead of including the pagination links as part of the body of the response, for example:


-

Link Header

+

Link Header

A custom pagination style, using the 'Link' header'


HTML pagination controls

@@ -674,6 +672,8 @@ class StandardResultsSetPagination(PageNumberPagination):

DRF-extensions

The DRF-extensions package includes a PaginateByMaxMixin mixin class that allows your API clients to specify ?page_size=max to obtain the maximum allowed page size.

+ +
@@ -697,6 +697,8 @@ class StandardResultsSetPagination(PageNumberPagination): + + - +
+
+ +
+
+
- - - - parsers.py - - + -

Parsers

+ + + + parsers.py + + + + +

Parsers

Machine interacting web services tend to use more structured formats for sending data than form-encoded, since they're @@ -597,6 +595,8 @@ def parse(self, stream, media_type=None, parser_context=None):

CamelCase JSON

djangorestframework-camel-case provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by Vitaly Babiy.

+ +
@@ -620,6 +620,8 @@ def parse(self, stream, media_type=None, parser_context=None): + + - +
+
+ +
+
+
- - - - permissions.py - - + -

Permissions

+ + + + permissions.py + + + + +

Permissions

Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.

Apple Developer Documentation

-

Together with authentication and throttling, permissions determine whether a request should be granted or denied access.

+

Together with authentication and throttling, permissions determine whether a request should be granted or denied access.

Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the request.user and request.auth properties to determine if the incoming request should be permitted.

Permissions are used to grant or deny access different classes of users to different parts of the API.

The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds the IsAuthenticated class in REST framework.

@@ -483,7 +477,7 @@ or if you override the get_object method on a generic view, then yo

Limitations of object level permissions

For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects.

-

Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.

+

Often when you're using object level permissions you'll also want to filter the queryset appropriately, to ensure that users only have visibility onto instances that they are permitted to view.

Setting the permission policy

The default permission policy may be set globally, using the DEFAULT_PERMISSION_CLASSES setting. For example.

REST_FRAMEWORK = {
@@ -611,17 +605,17 @@ class BlacklistPermission(permissions.BasePermission):
         return obj.owner == request.user
 

Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling self.check_object_permissions(request, obj) from the view once you have the object instance. This call will raise an appropriate APIException if any object-level permission checks fail, and will otherwise simply return.

-

Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.

+

Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the filtering documentation for more details.


Third party packages

The following third party packages are also available.

-

DRF Any Permissions

-

The DRF Any Permissions packages provides a different permission behavior in contrast to REST framework. Instead of all specified permissions being required, only one of the given permissions has to be true in order to get access to the view.

Composed Permissions

The Composed Permissions package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.

REST Condition

The REST Condition package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators.

+ +
@@ -645,6 +639,8 @@ class BlacklistPermission(permissions.BasePermission): + + - +
+
+ +
+
+
- - - - relations.py - - + -

Serializer relations

+ + + + relations.py + + + + +

Serializer relations

Bad programmers worry about the code. Good programmers worry about data structures and their relationships.

@@ -841,6 +839,8 @@ attributes are not configured to correctly match the URL conf.

DRF Nested Routers

The drf-nested-routers package provides routers and relationship fields for working with nested resources.

+ +
@@ -864,6 +864,8 @@ attributes are not configured to correctly match the URL conf.

+ + - +
+
+ +
+
+
- - - - renderers.py - - + -

Renderers

+ + + + renderers.py + + + + +

Renderers

Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.

Django documentation

@@ -513,7 +511,7 @@

How the renderer is determined

The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.

The basic process of content negotiation involves examining the request's Accept header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL http://example.com/api/users_count.json might be an endpoint that always returns JSON data.

-

For more information see the documentation on content negotiation.

+

For more information see the documentation on content negotiation.

Setting the renderers

The default set of renderers may be set globally, using the DEFAULT_RENDERER_CLASSES setting. For example, the following settings would use JSON as the main media type and also include the self describing API.

REST_FRAMEWORK = {
@@ -635,7 +633,7 @@ def simple_html_view(request):
         return JSONRenderer()
 

MultiPartRenderer

-

This renderer is used for rendering HTML multipart form data. It is not suitable as a response renderer, but is instead used for creating test requests, using REST framework's test client and test request factory.

+

This renderer is used for rendering HTML multipart form data. It is not suitable as a response renderer, but is instead used for creating test requests, using REST framework's test client and test request factory.

.media_type: multipart/form-data; boundary=BoUnDaRyStRiNg

.format: '.multipart'

.charset: utf-8

@@ -804,6 +802,8 @@ In this case you can underspecify the media types it should respond to, by using

Pandas (CSV, Excel, PNG)

Django REST Pandas provides a serializer and renderers that support additional data processing and output via the Pandas DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both .xls and .xlsx), and a number of other formats. It is maintained by S. Andrew Sheppard as part of the wq Project.

+ +
@@ -827,6 +827,8 @@ In this case you can underspecify the media types it should respond to, by using + + - +
+
+ +
+
+
- - - - request.py - - + -

Requests

+ + + + request.py + + + + +

Requests

If you're doing REST-based web service stuff ... you should ignore request.POST.

— Malcom Tredinnick, Django developers group

@@ -476,7 +474,7 @@
  • It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests.
  • It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.
  • -

    For more details see the parsers documentation.

    +

    For more details see the parsers documentation.

    .query_params

    request.query_params is a more correctly named synonym for request.GET.

    For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests.

    @@ -508,11 +506,11 @@

    .user

    request.user typically returns an instance of django.contrib.auth.models.User, although the behavior depends on the authentication policy being used.

    If the request is unauthenticated the default value of request.user is an instance of django.contrib.auth.models.AnonymousUser.

    -

    For more details see the authentication documentation.

    +

    For more details see the authentication documentation.

    .auth

    request.auth returns any additional authentication context. The exact behavior of request.auth depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against.

    If the request is unauthenticated, or if no additional context is present, the default value of request.auth is None.

    -

    For more details see the authentication documentation.

    +

    For more details see the authentication documentation.

    .authenticators

    The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Authentication instances, based on the authentication_classes set on the view or based on the DEFAULT_AUTHENTICATORS setting.

    You won't typically need to access this property.

    @@ -522,22 +520,24 @@

    .method

    request.method returns the uppercased string representation of the request's HTTP method.

    Browser-based PUT, PATCH and DELETE forms are transparently supported.

    -

    For more information see the browser enhancements documentation.

    +

    For more information see the browser enhancements documentation.

    .content_type

    request.content_type, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided.

    You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior.

    If you do need to access the content type of the request you should use the .content_type property in preference to using request.META.get('HTTP_CONTENT_TYPE'), as it provides transparent support for browser-based non-form content.

    -

    For more information see the browser enhancements documentation.

    +

    For more information see the browser enhancements documentation.

    .stream

    request.stream returns a stream representing the content of the request body.

    You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.

    If you do need to access the raw content directly, you should use the .stream property in preference to using request.content, as it provides transparent support for browser-based non-form content.

    -

    For more information see the browser enhancements documentation.

    +

    For more information see the browser enhancements documentation.


    Standard HttpRequest attributes

    As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal.

    Note that due to implementation reasons the Request class does not inherit from HttpRequest class, but instead extends the class using composition.

    + +
    @@ -561,6 +561,8 @@ + + - +
    +
    + +
    +
    +
    - - - - response.py - - + -

    Responses

    + + + + response.py + + + + +

    Responses

    Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.

    Django documentation

    @@ -447,7 +445,7 @@

    Arguments:

    @@ -505,6 +505,8 @@ response['Cache-Control'] = 'no-cache' + + - +
    +
    + +
    +
    +
    - - - - reverse.py - - + -

    Returning URLs

    + + + + reverse.py + + + + +

    Returning URLs

    The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.

    — Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures

    @@ -415,6 +413,8 @@ class APIRootView(APIView):
    api_root = reverse_lazy('api-root', request=request)
     
    + +
    @@ -438,6 +438,8 @@ class APIRootView(APIView): + + - +
    +
    + +
    +
    +
    - - - - routers.py - - + -

    Routers

    + + + + routers.py + + + + +

    Routers

    Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.

    Ruby on Rails Documentation

    @@ -526,7 +524,7 @@ class UserViewSet(ModelViewSet): -

    For more information see the viewset documentation on marking extra actions for routing.

    +

    For more information see the viewset documentation on marking extra actions for routing.

    API Guide

    SimpleRouter

    This router includes routes for the standard set of list, create, retrieve, update, partial_update and destroy actions. The viewset can also mark additional methods to be routed, using the @detail_route or @list_route decorators.

    @@ -672,6 +670,8 @@ rest.router.register_model(MyModel)

    DRF-extensions

    The DRF-extensions package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.

    + +
    @@ -695,6 +695,8 @@ rest.router.register_model(MyModel) + + - +
    +
    + +
    +
    +
    - - - - serializers.py - - + -

    Serializers

    + + + + serializers.py + + + + +

    Serializers

    Expanding the usefulness of the serializers is something that we would like to address. However, it's not a trivial problem, and it @@ -742,7 +740,7 @@ class GameRecord(serializers.Serializer): fields=['room_number', 'date'] ) -

    For more information see the validators documentation.

    +

    For more information see the validators documentation.

    Accessing the initial data and instance

    When passing an initial object or queryset to a serializer instance, the object will be made available as .instance. If no initial object is passed then the .instance attribute will be None.

    When passing data to a serializer instance, the unmodified data will be made available as .initial_data. If the data keyword argument is not passed then the .initial_data attribute will not exist.

    @@ -861,7 +859,7 @@ serializer.errors has_support_contract=validated_data['profile']['has_support_contract'] ) -

    For more details on this approach see the Django documentation on model managers, and this blogpost on using model and manager classes.

    +

    For more details on this approach see the Django documentation on model managers, and this blogpost on using model and manager classes.

    Dealing with multiple objects

    The Serializer class can also handle serializing or deserializing lists of objects.

    Serializing multiple objects

    @@ -959,7 +957,7 @@ AccountSerializer():

    One example of this is a read-only relation to the currently authenticated User which is unique_together with another identifier. In this case you would declare the user field like so:

    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
     
    -

    Please review the Validators Documentation for details on the UniqueTogetherValidator and CurrentUserDefault classes.

    +

    Please review the Validators Documentation for details on the UniqueTogetherValidator and CurrentUserDefault classes.


    Additional keyword arguments

    There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the extra_kwargs option. Similarly to read_only_fields this means you do not need to explicitly declare the field on the serializer.

    @@ -982,7 +980,7 @@ AccountSerializer():

    Relational fields

    When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for ModelSerializer is to use the primary keys of the related instances.

    Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.

    -

    For full details see the serializer relations documentation.

    +

    For full details see the serializer relations documentation.

    Inheritance of the 'Meta' class

    The inner Meta class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's Model and ModelForm classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example:

    class AccountSerializer(MyBaseSerializer):
    @@ -1346,6 +1344,8 @@ def all_high_scores(request):
     

    HStoreSerializer

    The django-rest-framework-hstore package provides an HStoreSerializer to support django-hstore DictionaryField model field and its schema-mode feature.

    + +
    @@ -1369,6 +1369,8 @@ def all_high_scores(request): + + - +
    +
    + +
    +
    +
    - - - - settings.py - - + -

    Settings

    + + + + settings.py + + + + +

    Settings

    Namespaces are one honking great idea - let's do more of those!

    The Zen of Python

    @@ -687,6 +685,8 @@ If set to None then generic filtering is disabled.

    An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to None then less strict IP matching will be used by the throttle classes.

    Default: None

    + +
    @@ -710,6 +710,8 @@ If set to None then generic filtering is disabled.

    + + - +
    +
    + +
    +
    +
    - - - - status.py - - + -

    Status Codes

    + + + + status.py + + + + +

    Status Codes

    418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

    RFC 2324, Hyper Text Coffee Pot Control Protocol

    @@ -487,6 +485,8 @@ is_client_error() # 4xx is_server_error() # 5xx
    + +
    @@ -510,6 +510,8 @@ is_server_error() # 5xx + + - +
    +
    + +
    +
    +
    - - - - test.py - - + -

    Testing

    + + + + test.py + + + + +

    Testing

    Code without tests is broken as designed.

    Jacob Kaplan-Moss

    @@ -651,6 +649,8 @@ self.assertEqual(response.content, '{"username": "lauren", "id": 4}') } + +
    @@ -674,6 +674,8 @@ self.assertEqual(response.content, '{"username": "lauren", "id": 4}') + + - +
    +
    + +
    +
    +
    - - - - throttling.py - - + -

    Throttling

    + + + + throttling.py + + + + +

    Throttling

    HTTP/1.1 420 Enhance Your Calm

    Twitter API rate limiting response

    -

    Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.

    +

    Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.

    As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.

    Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.

    Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.

    @@ -558,6 +556,8 @@ class UploadView(APIView): return random.randint(1, 10) == 1 + +
    @@ -581,6 +581,8 @@ class UploadView(APIView): + + - +
    +
    + +
    +
    +
    - - - - validators.py - - + -

    Validators

    + + + + validators.py + + + + +

    Validators

    Validators can be useful for re-using validation logic between different types of fields.

    Django documentation

    @@ -582,7 +580,7 @@ It has two required arguments, and a single optional messages argum self.base = base def __call__(self, value): - if value % self.base != 0 + if value % self.base != 0: message = 'This field must be a multiple of %d.' % self.base raise serializers.ValidationError(message) @@ -594,6 +592,8 @@ It has two required arguments, and a single optional messages argum self.is_update = serializer_field.parent.instance is not None + +
    @@ -617,6 +617,8 @@ It has two required arguments, and a single optional messages argum + + - +
    +
    + +
    +
    +
    - - - - versioning.py - - + -

    Versioning

    + + + + versioning.py + + + + +

    Versioning

    Versioning an interface is just a "polite" way to kill deployed clients.

    Roy Fielding.

    @@ -563,6 +561,8 @@ Accept: application/json

    If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the .reverse() method on the class. See the source code for examples.

    + +
    @@ -586,6 +586,8 @@ Accept: application/json + + - +
    +
    + +
    +
    +
    - - - - decorators.py - - - - views.py - - + -

    Class Based Views

    + + + + decorators.py + + + + views.py + + + + +

    Class Based Views

    Django's class based views are a welcome departure from the old-style views.

    Reinout van Rees

    @@ -494,7 +492,7 @@ This method is used to enforce permissions and throttling, and perform content n def hello_world(request): return Response({"message": "Hello, world!"}) -

    This view will use the default renderers, parsers, authentication classes etc specified in the settings.

    +

    This view will use the default renderers, parsers, authentication classes etc specified in the settings.

    By default only GET methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:

    @api_view(['GET', 'POST'])
     def hello_world(request):
    @@ -503,7 +501,7 @@ def hello_world(request):
         return Response({"message": "Hello, world!"})
     

    API policy decorators

    -

    To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come after (below) the @api_view decorator. For example, to create a view that uses a throttle to ensure it can only be called once per day by a particular user, use the @throttle_classes decorator, passing a list of throttle classes:

    +

    To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come after (below) the @api_view decorator. For example, to create a view that uses a throttle to ensure it can only be called once per day by a particular user, use the @throttle_classes decorator, passing a list of throttle classes:

    from rest_framework.decorators import api_view, throttle_classes
     from rest_framework.throttling import UserRateThrottle
     
    @@ -526,6 +524,8 @@ def view(request):
     
     

    Each of these decorators takes a single argument which must be a list or tuple of classes.

    + +
    @@ -549,6 +549,8 @@ def view(request): + + - +
    +
    + +
    +
    +
    - - - - viewsets.py - - + -

    ViewSets

    + + + + viewsets.py + + + + +

    ViewSets

    After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.

    Ruby on Rails Documentation

    @@ -584,7 +582,7 @@ class UserViewSet(viewsets.ModelViewSet): def get_queryset(self): return self.request.user.accounts.all()
    -

    Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify the base_name kwarg as part of your router registration.

    +

    Note however that upon removal of the queryset property from your ViewSet, any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify the base_name kwarg as part of your router registration.

    Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.

    ReadOnlyModelViewSet

    The ReadOnlyModelViewSet class also inherits from GenericAPIView. As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve().

    @@ -616,6 +614,8 @@ class UserViewSet(viewsets.ModelViewSet):

    By creating your own base ViewSet classes, you can provide common behavior that can be reused in multiple viewsets across your API.

    + +
    @@ -639,6 +639,8 @@ class UserViewSet(viewsets.ModelViewSet): + + - +
    +
    + +
    +
    +
    + -

    + + +

    @@ -474,7 +472,7 @@ clip: rect(0,0,0,0); border: 0;">Django REST Framework -Django REST Framework +Django REST Framework

    Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.

    @@ -659,6 +657,8 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    + +
    @@ -682,6 +682,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    + + - +
    +
    + +
    +
    +
    + -

    Django REST framework 3.0

    + + +

    Django REST framework 3.0

    The 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.

    This release is incremental in nature. There are some breaking API changes, and upgrading will require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.

    The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.

    @@ -993,7 +991,7 @@ class OrganizationSerializer(serializers.Serializer):

    The UniqueForDateValidator classes.

    REST framework also now includes explicit validator classes for validating the unique_for_date, unique_for_month, and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean().

    -

    These classes are documented in the Validators section of the documentation.

    +

    These classes are documented in the Validators section of the documentation.


    Generic views

    Simplification of view logic.

    @@ -1143,6 +1141,8 @@ amount = serializers.DecimalField(

    The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.

    You can follow development on the GitHub site, where we use milestones to indicate planning timescales.

    + +
    @@ -1166,6 +1166,8 @@ amount = serializers.DecimalField( + + - +
    +
    + +
    +
    +
    + -

    Django REST framework 3.1

    + + +

    Django REST framework 3.1

    The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.

    Some highlights include:

    @@ -560,6 +560,8 @@ Host: example.org + + - +
    +
    + +
    +
    +
    + -

    Working with AJAX, CSRF & CORS

    + + +

    Working with AJAX, CSRF & CORS

    "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."

    Jeff Atwood

    @@ -397,6 +395,8 @@

    The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.

    Otto Yiu maintains the django-cors-headers package, which is known to work correctly with REST framework APIs.

    + +
    @@ -420,6 +420,8 @@ + + - +
    +
    + +
    +
    +
    + -

    The Browsable API

    + + +

    The Browsable API

    It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.

    Alfred North Whitehead, An Introduction to Mathematics (1911)

    API may stand for Application Programming Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the HTML format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using POST, PUT, and DELETE.

    URLs

    -

    If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The rest_framework package includes a reverse helper for this purpose.

    +

    If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The rest_framework package includes a reverse helper for this purpose.

    Formats

    By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using ?format= in the request, so you can look at the raw JSON response in a browser by adding ?format=json to the URL. There are helpful extensions for viewing JSON in Firefox and Chrome.

    Customizing

    @@ -411,10 +409,10 @@

    For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style block.


    -

    Cerulean theme

    +

    Cerulean theme

    Screenshot of the bootswatch 'Cerulean' theme


    -

    Slate theme

    +

    Slate theme

    Screenshot of the bootswatch 'Slate' theme


    Blocks

    @@ -482,6 +480,8 @@

    Better support for autocomplete inputs is planned in future versions.


    + +
    @@ -505,6 +505,8 @@ + + - +
    +
    + +
    +
    +
    + -

    Browser enhancements

    + + +

    Browser enhancements

    "There are two noncontroversial uses for overloaded POST. The first is to simulate HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"

    RESTful Web Services, Leonard Richardson & Sam Ruby.

    @@ -440,6 +438,8 @@ was later dropped ongoing discussion about adding support for PUT and DELETE, as well as how to support content types other than form-encoded data.

    + +
    @@ -463,6 +463,8 @@ as well as how to support content types other than form-encoded data.

    + + - +
    +
    + +
    +
    +
    + -

    Contributing to REST framework

    + + +

    Contributing to REST framework

    The world can only really be changed one piece at a time. The art is picking that piece.

    Tim Berners-Lee

    @@ -505,7 +503,7 @@ pip install -r requirements.txt

    GitHub's documentation for working on pull requests is available here.

    Always run the tests before submitting pull requests, and ideally run tox in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.

    Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.

    -

    Travis status

    +

    Travis status

    Above: Travis build notifications

    Managing compatibility issues

    Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the compat.py module, and should provide a single common interface that the rest of the codebase can use.

    @@ -559,6 +557,8 @@ More text... --- + +
    @@ -582,6 +582,8 @@ More text... + + - +
    +
    + +
    +
    +
    + -

    Documenting your API

    + + +

    Documenting your API

    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

    @@ -387,19 +385,19 @@

    Marc Gibbons' Django REST Swagger integrates REST framework with the Swagger API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.

    The package is fully documented, well supported, and comes highly recommended.

    Django REST Swagger supports REST framework versions 2.3 and above.

    -

    Screenshot - Django REST Swagger

    +

    Screenshot - Django REST Swagger


    REST Framework Docs

    The REST Framework Docs package is an earlier project, also by Marc Gibbons, that offers clean, simple autogenerated documentation for your API.

    -

    Screenshot - REST Framework Docs

    +

    Screenshot - REST Framework Docs


    Apiary

    There are various other online tools and services for providing API documentation. One notable service is Apiary. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools.

    -

    Screenshot - Apiary

    +

    Screenshot - Apiary


    Self describing APIs

    The 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.

    -

    Screenshot - Self describing API

    +

    Screenshot - Self describing API


    Setting the title

    The title that is used in the browsable API is generated from the view class name or function name. Any trailing View or ViewSet suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.

    @@ -434,7 +432,9 @@

    The hypermedia approach

    To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.

    In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the media types 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.

    -

    To 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 REST, Hypermedia & HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.

    +

    To 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 REST, Hypermedia & HATEOAS section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.

    + +
    @@ -459,6 +459,8 @@ + + - +
    +
    + +
    +
    +
    + -

    Internationalization

    + + +

    Internationalization

    Supporting internationalization is not optional. It must be a core feature.

    Jannis Leidel, speaking at Django Under the Hood, 2015.

    @@ -411,7 +409,7 @@ Host: example.org

    Note 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 400 Bad Request response body might look like this:

    {"detail": {"username": ["Esse campo deve ser unico."]}}
     
    -

    If you want to use different string for parts of the response such as detail and non_field_errors then you can modify this behavior by using a custom exception handler.

    +

    If you want to use different string for parts of the response such as detail and non_field_errors then you can modify this behavior by using a custom exception handler.

    Specifying the set of supported languages.

    By default all available languages will be supported.

    If you only wish to support a subset of the available languages, use Django's standard LANGUAGES setting:

    @@ -464,6 +462,8 @@ available for Django to use. You should see a message like processing file

    For API clients the most appropriate of these will typically be to use the Accept-Language header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an Accept-Language header for API clients rather than using language URL prefixes.

    + +
    @@ -487,6 +487,8 @@ available for Django to use. You should see a message like processing file + + - +
    +
    + +
    +
    +
    + -

    Kickstarting Django REST framework 3

    + + +

    Kickstarting Django REST framework 3


    @@ -504,6 +502,8 @@

    Supporters

    There 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!

    + +
    @@ -527,6 +527,8 @@ + + - +
    +
    + +
    +
    +
    + -

    Project management

    + + +

    Project management

    "No one can whistle a symphony; it takes a whole orchestra to play it"

    — Halford E. Luccock

    @@ -465,9 +463,15 @@ To modify this process for future maintenance cycles make a pull request to the
    Release manager is @***.
     Pull request is #***.
     
    +During development cycle:
    +
    +- [ ] Upload the new content to be translated to [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).
    +
    +
     Checklist:
     
     - [ ] Create pull request for [release notes](https://github.com/tomchristie/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/tomchristie/django-rest-framework/milestones/***).
    +- [ ] Update the translations from [transifex](http://www.django-rest-framework.org/topics/project-management/#translations).
     - [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/__init__.py).
     - [ ] Confirm with @tomchristie that release is finalized and ready to go.
     - [ ] Ensure that release date is included in pull request.
    @@ -538,6 +542,8 @@ django-admin.py compilemessages
     
  • Document ownership and management of the security mailing list.
  • + +
    @@ -561,6 +567,8 @@ django-admin.py compilemessages + + - +
    +
    + +
    +
    +
    + -

    Release Notes

    + + +

    Release Notes

    Release Early, Release Often

    — Eric S. Raymond, The Cathedral and the Bazaar.

    @@ -415,6 +413,22 @@

    3.1.x series

    +

    3.1.3

    +

    Date: 4th June 2015.

    +
      +
    • Add DurationField. (#2481, #2989)
    • +
    • Add format argument to UUIDField. (#2788, #3000)
    • +
    • MultipleChoiceField empties incorrectly on a partial update using multipart/form-data (#2993, #2894)
    • +
    • Fix a bug in options related to read-only RelatedField. (#2981, #2811)
    • +
    • Fix nested serializers with unique_together relations. (#2975)
    • +
    • Allow unexpected values for ChoiceField/MultipleChoiceField representations. (#2839, #2940)
    • +
    • Rollback the transaction on error if ATOMIC_REQUESTS is set. (#2887, #2034)
    • +
    • Set the action on a view when override_method regardless of its None-ness. (#2933)
    • +
    • DecimalField accepts 2E+2 as 200 and validates decimal place correctly. (#2948, #2947)
    • +
    • Support basic authentication with custom UserModel that change username. (#2952)
    • +
    • IPAddressField improvements. (#2747, #2618, #3008)
    • +
    • Improve DecimalField for easier subclassing. (#2695)
    • +

    3.1.2

    Date: 13rd May 2015.

      @@ -422,12 +436,12 @@
    • Use default reason phrases from HTTP standard. (#2764, #2763)
    • Raise error when ModelSerializer used with abstract model. (#2757, #2630)
    • Handle reversal of non-API view_name in HyperLinkedRelatedField (#2724, #2711)
    • -
    • Dont require pk strictly for related fields. (#2745, #2754)
    • +
    • Dont require pk strictly for related fields. (#2745, #2754)
    • Metadata detects null boolean field type. (#2762)
    • Proper handling of depth in nested serializers. (#2798)
    • Display viewset without paginator. (#2807)
    • Don't check for deprecated .model attribute in permissions (#2818)
    • -
    • Restrict integer field to integers and strings. (#2835, #2836)
    • +
    • Restrict integer field to integers and strings. (#2835, #2836)
    • Improve IntegerField to use compiled decimal regex. (#2853)
    • Prevent empty queryset to raise AssertionError. (#2862)
    • DjangoModelPermissions rely on get_queryset. (#2863)
    • @@ -451,7 +465,7 @@

    3.1.0

    Date: 5th March 2015.

    -

    For full details see the 3.1 release announcement.

    +

    For full details see the 3.1 release announcement.


    3.0.x series

    3.0.5

    @@ -539,7 +553,7 @@

    3.0.0

    Date: 1st December 2014

    -

    For full details see the 3.0 release announcement.

    +

    For full details see the 3.0 release announcement.


    For older release notes, please see the version 2.x documentation.

    @@ -549,7 +563,10 @@ -

    + +

    + +
    @@ -574,6 +591,8 @@ + + - +
    +
    + +
    +
    +
    + -

    REST, Hypermedia & HATEOAS

    + + +

    REST, Hypermedia & HATEOAS

    You keep using that word "REST". I do not think it means what you think it means.

    — Mike Amundsen, REST fest 2012 keynote.

    @@ -396,10 +394,12 @@ the Design of Network-based Software Architectures.

    REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style.

    What REST framework provides.

    It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.

    -

    REST framework also includes serialization and parser/renderer components that make it easy to build appropriate media types, hyperlinked relations for building well-connected systems, and great support for content negotiation.

    +

    REST framework also includes serialization and parser/renderer components that make it easy to build appropriate media types, hyperlinked relations for building well-connected systems, and great support for content negotiation.

    What REST framework doesn't provide.

    What REST framework doesn't do is give you is machine readable hypermedia formats such as HAL, Collection+JSON, JSON API or HTML microformats by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.

    + +
    @@ -423,6 +423,8 @@ the Design of Network-based Software Architectures. + + - +
    +
    + +
    +
    +
    + -

    Third Party Resources

    + + +

    Third Party Resources

    Software ecosystems […] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills.

    Jan Bosch.

    @@ -488,7 +486,7 @@ You probably want to also tag the version now:

    Adding to the Django REST framework grid

    We suggest adding your package to the REST Framework grid on Django Packages.

    Adding to the Django REST framework docs

    -

    Create a Pull Request or Issue on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under Third party packages of the API Guide section that best applies, like Authentication or Permissions. You can also link your package under the [Third Party Resources][third-party-resources] section.

    +

    Create a Pull Request or Issue on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under Third party packages of the API Guide section that best applies, like Authentication or Permissions. You can also link your package under the [Third Party Resources][third-party-resources] section.

    Announce on the discussion group.

    You can also let others know about your package through the discussion group.

    Existing Third Party Packages

    @@ -557,6 +555,7 @@ You probably want to also tag the version now:
  • drf-extensions - A collection of custom extensions
  • ember-django-adapter - An adapter for working with Ember.js
  • django-versatileimagefield - Provides a drop-in replacement for Django's stock ImageField that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, click here.
  • +
  • drf-tracking - Utilities to track requests to DRF API views.
  • Other Resources

    Tutorials

    @@ -582,6 +581,12 @@ You probably want to also tag the version now:
  • Web API performance: profiling Django REST framework
  • API Development with Django and Django REST Framework
  • +

    Documentations

    + + +
    @@ -606,6 +611,8 @@ You probably want to also tag the version now: + + - +
    +
    + +
    +
    +
    + -

    Tutorial 1: Serialization

    + + +

    Tutorial 1: Serialization

    Introduction

    This 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.

    -

    The 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 quickstart documentation instead.

    +

    The 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 quickstart documentation instead.


    Note: The code for this tutorial is available in the tomchristie/rest-framework-tutorial repository on GitHub. The completed implementation is also online as a sandbox version for testing, available here.


    @@ -720,7 +718,9 @@ HTTP/1.1 200 OK

    Where are we now

    We'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.

    Our API views don't do anything particularly special at the moment, beyond serving json responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API.

    -

    We'll see how we can start to improve things in part 2 of the tutorial.

    +

    We'll see how we can start to improve things in part 2 of the tutorial.

    + +
    @@ -745,6 +745,8 @@ HTTP/1.1 200 OK + + - +
    +
    + +
    +
    +
    + -

    Tutorial 2: Requests and Responses

    + + +

    Tutorial 2: Requests and Responses

    From this point we're going to really start covering the core of REST framework. Let's introduce a couple of essential building blocks.

    Request objects

    @@ -494,7 +492,7 @@ urlpatterns = format_suffix_patterns(urlpatterns)

    We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.

    How's it looking?

    -

    Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.

    +

    Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.

    We can get a list of all of the snippets, as before.

    http http://127.0.0.1:8000/snippets/
     
    @@ -556,9 +554,11 @@ http --json POST http://127.0.0.1:8000/snippets/ code="print 456"
     

    Browsability

    Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.

    Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.

    -

    See the browsable api topic for more information about the browsable API feature and how to customize it.

    +

    See the browsable api topic for more information about the browsable API feature and how to customize it.

    What's next?

    -

    In tutorial part 3, we'll start using class based views, and see how generic views reduce the amount of code we need to write.

    +

    In tutorial part 3, we'll start using class based views, and see how generic views reduce the amount of code we need to write.

    + +
    @@ -583,6 +583,8 @@ http --json POST http://127.0.0.1:8000/snippets/ code="print 456" + + - +
    +
    + +
    +
    +
    + -

    Tutorial 3: Class Based Views

    + + +

    Tutorial 3: Class Based Views

    We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code DRY.

    Rewriting our API using class based views

    We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring of views.py.

    @@ -502,7 +500,9 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = SnippetSerializer

    Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.

    -

    Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can deal with authentication and permissions for our API.

    +

    Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can deal with authentication and permissions for our API.

    + +
    @@ -527,6 +527,8 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): + + - +
    +
    + +
    +
    +
    + -

    Tutorial 4: Authentication & Permissions

    + + +

    Tutorial 4: Authentication & Permissions

    Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:

    @@ -594,6 +594,8 @@ class IsOwnerOrReadOnly(permissions.BasePermission): + + - +
    +
    + +
    +
    +
    + -

    Tutorial 5: Relationships & Hyperlinked APIs

    + + +

    Tutorial 5: Relationships & Hyperlinked APIs

    At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.

    Creating an endpoint for the root of our API

    Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the @api_view decorator we introduced earlier. In your snippets/views.py add:

    @@ -516,7 +514,9 @@ urlpatterns += [

    Browsing the API

    If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.

    You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.

    -

    In part 6 of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.

    +

    In part 6 of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.

    + +
    @@ -541,6 +541,8 @@ urlpatterns += [ + + - +
    +
    + +
    +
    +
    + -

    Tutorial 6: ViewSets & Routers

    + + +

    Tutorial 6: ViewSets & Routers

    REST framework includes an abstraction for dealing with ViewSets, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.

    ViewSet classes are almost the same thing as View classes, except that they provide operations such as read, or update, and not method handlers such as get or put.

    A ViewSet class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a Router class which handles the complexities of defining the URL conf for you.

    @@ -505,6 +503,8 @@ urlpatterns = [

    Now go build awesome things.

    + +
    @@ -528,6 +528,8 @@ urlpatterns = [ + + - +
    +
    + +
    +
    +
    + -

    Quickstart

    + + +

    Quickstart

    We're going to create a simple API to allow admin users to view and edit the users and groups in the system.

    Project setup

    Create a new Django project named tutorial, then start a new app called quickstart.

    @@ -544,10 +542,12 @@ HTTP/1.1 200 OK }

    Or directly through the browser...

    -

    Quick start image

    +

    Quick start image

    If you're working through the browser, make sure to login using the control in the top right corner.

    Great, that was easy!

    -

    If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.

    +

    If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.

    + +
    @@ -572,6 +572,8 @@ HTTP/1.1 200 OK + +