404
-Page not found + +
diff --git a/404.html b/404.html index 38b436a53..484d2b2c0 100644 --- a/404.html +++ b/404.html @@ -4,18 +4,18 @@
--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.
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.
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.
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.
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.
+ +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): }) + +
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".
+ +
Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.
@@ -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 auuid.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')
+
+- +
format
: Determines the representation format of the uuid value+
+- +
'hex_verbose'
- The cannoncical hex representation, including hyphens:"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
- +
'hex'
- The compact hex representation of the UUID, not including hyphens:"5ce0e9a55ffa654bcee01238041fb31a"
- +
'int'
- A 128 bit integer representation of the UUID:"123456789012312313134124512351145145114"
- +
'urn'
- RFC 4122 URN representation of the UUID:"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
+ Changing theformat
parameters only affects representation values. All formats are accepted byto_internal_value
IPAddressField
+A field that ensures the input is a valid IPv4 or IPv6 string.
+Corresponds to
+django.forms.fields.IPAddressField
anddjango.forms.fields.GenericIPAddressField
.Signature:
+IPAddressField(protocol='both', unpack_ipv4=False, **options)
+
- +
protocol
Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.- +
unpack_ipv4
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'.
Numeric fields
IntegerField
@@ -761,6 +786,13 @@ color_channel = serializers.ChoiceField(
TimeField
format stringsFormat 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 adatetime.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
@@ -979,6 +1011,8 @@ def to_internal_value(self, data):ModelSerializer
to correspond to custom model field classes.django-rest-framework-hstore
The django-rest-framework-hstore package provides an
+ +HStoreField
to support django-hstoreDictionaryField
model field.
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.
@@ -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.
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.
+ +
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.
@@ -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.
+ +
[The
@@ -469,6 +467,8 @@ def schema(self, request): } + +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.
Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.
@@ -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:
-+
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 aPaginateByMaxMixin
mixin class that allows your API clients to specify?page_size=max
to obtain the maximum allowed page size.
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.
+ +
-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.
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.
get_object
method on a generic view, then yo
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.
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.
The following third party packages are also available.
-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.
The Composed Permissions package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components.
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.
+ +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.
+ +
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.
@@ -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 URLhttp://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 useJSON
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:
@@ -804,6 +802,8 @@ In this case you can underspecify the media types it should respond to, by usingutf-8
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.
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 ofPUT
andPATCH
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 forrequest.GET
.For clarity inside your code, we recommend using
@@ -508,11 +506,11 @@request.query_params
instead of the Django's standardrequest.GET
. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not justGET
requests..user
request.user
typically returns an instance ofdjango.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 ofdjango.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 ofrequest.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
isNone
.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 ofAuthentication
instances, based on theauthentication_classes
set on the view or based on theDEFAULT_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
andDELETE
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 usingrequest.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 usingrequest.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'sHttpRequest
, all the other standard attributes and methods are also available. For example therequest.META
andrequest.session
dictionaries are available as normal.Note that due to implementation reasons the
+ +Request
class does not inherit fromHttpRequest
class, but instead extends the class using composition.
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.
@@ -447,7 +445,7 @@Arguments:
- -
data
: The serialized data for the response.- +
status
: A status code for the response. Defaults to 200. See also status codes.status
: A status code for the response. Defaults to 200. See also status codes.template_name
: A template name to use ifHTMLRenderer
is selected.headers
: A dictionary of HTTP headers to use in the response.- @@ -482,6 +480,8 @@ response['Cache-Control'] = 'no-cache'
content_type
: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly.As with any other
TemplateResponse
, this method is called to render the serialized data of the response into the final response content. When.render()
is called, the response content will be set to the result of calling the.render(data, accepted_media_type, renderer_context)
method on theaccepted_renderer
instance.You won't typically need to call
+ +.render()
yourself, as it's handled by Django's standard response cycle.
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)
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.
@@ -526,7 +524,7 @@ class UserViewSet(ModelViewSet):-
- URL pattern:
^users/{pk}/change-password/$
Name:'user-change-password'
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
@@ -672,6 +670,8 @@ rest.router.register_model(MyModel)list
,create
,retrieve
,update
,partial_update
anddestroy
actions. The viewset can also mark additional methods to be routed, using the@detail_route
or@list_route
decorators.DRF-extensions
The
+ +DRF-extensions
package provides routers for creating nested viewsets, collection level controllers with customizable endpoint names.
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 beNone
.When passing data to a serializer instance, the unmodified data will be made available as
@@ -861,7 +859,7 @@ serializer.errors has_support_contract=validated_data['profile']['has_support_contract'] ) -.initial_data
. If the data keyword argument is not passed then the.initial_data
attribute will not exist.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 isunique_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
@@ -982,7 +980,7 @@ AccountSerializer():extra_kwargs
option. Similarly toread_only_fields
this means you do not need to explicitly declare the field on the serializer.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'sModel
andModelForm
classes. If you want theMeta
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-hstoreDictionaryField
model field and itsschema-mode
feature.
Namespaces are one honking great idea - let's do more of those!
@@ -687,6 +685,8 @@ If set toNone
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
None
then generic filtering is disabled.
+
+
- 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 + +
Code without tests is broken as designed.
@@ -651,6 +649,8 @@ self.assertEqual(response.content, '{"username": "lauren", "id": 4}') } + +
-HTTP/1.1 420 Enhance Your Calm
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 + +Validators can be useful for re-using validation logic between different types of fields.
@@ -582,7 +580,7 @@ It has two required arguments, and a single optionalmessages
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 optionalmessages
argum self.is_update = serializer_field.parent.instance is not None + +
messages
argum
+
+
- Versioning an interface is just a "polite" way to kill deployed clients.
— Roy Fielding.
@@ -563,6 +561,8 @@ Accept: application/jsonIf 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.
Django's class based views are a welcome departure from the old-style views.
@@ -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.
+ +
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.
@@ -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 yourViewSet
, any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify thebase_name
kwarg as part of your router registration.Note however that upon removal of the
queryset
property from yourViewSet
, any associated router will be unable to derive the base_name of your Model automatically, and so you will have to specify thebase_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
@@ -616,6 +614,8 @@ class UserViewSet(viewsets.ModelViewSet):ReadOnlyModelViewSet
class also inherits fromGenericAPIView
. As withModelViewSet
it also includes implementations for various actions, but unlikeModelViewSet
only provides the 'read-only' actions,.list()
and.retrieve()
.By creating your own base
+ +ViewSet
classes, you can provide common behavior that can be reused in multiple viewsets across your API.
+ + +
@@ -474,7 +472,7 @@
clip: rect(0,0,0,0);
border: 0;">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. + +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):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.
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.
+ +The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality.
Some highlights include:
The pagination API has been improved, making it both easier to use, and more powerful.
-A guide to the headline features follows. For full details, see the pagination documentation.
+A guide to the headline features follows. For full details, see the pagination documentation.
Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes.
PAGINATE_BY
settings key will continue to work but is now pending deprecation. The more obviously named PAGE_SIZE
settings key should now be used instead.The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for this blog post on the subject.
Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API:
-The cursor based pagination renders a more simple style of control:
-The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the Link
or Content-Range
headers.
For more information, see the custom pagination styles documentation.
+For more information, see the custom pagination styles documentation.
We've made it easier to build versioned APIs. Built-in schemes for versioning include both URL based and Accept header based variations.
+We've made it easier to build versioned APIs. Built-in schemes for versioning include both URL based and Accept header based variations.
When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request.
For example, when using NamespaceVersioning
, and the following hyperlinked serializer:
class AccountsSerializer(serializer.HyperlinkedModelSerializer):
@@ -451,7 +449,7 @@
REST framework now includes a built-in set of translations, and supports internationalized error responses. This allows you to either change the default language, or to allow clients to specify the language via the Accept-Language
header.
REST framework now includes a built-in set of translations, and supports internationalized error responses. This allows you to either change the default language, or to allow clients to specify the language via the Accept-Language
header.
You can change the default language by using the standard Django LANGUAGE_CODE
setting:
LANGUAGE_CODE = "es-es"
@@ -475,7 +473,7 @@ Host: example.org
"detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."
}
-Note that the structure of the error responses is still the same. We still have a details
key in the response. If needed you can modify this behavior too, by using a custom exception handler.
Note that the structure of the error responses is still the same. We still have a details
key in the response. If needed you can modify this behavior too, by using a custom exception handler.
We include built-in translations both for standard exception cases, and for serializer validation errors.
The full list of supported languages can be found on our Transifex project page.
If you only wish to support a subset of the supported languages, use Django's standard LANGUAGES
setting:
For more details, see the internationalization documentation.
+For more details, see the internationalization documentation.
Many thanks to Craig Blaszczyk for helping push this through.
The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships.
-For more information, see the documentation on customizing field mappings for ModelSerializer classes.
+For more information, see the documentation on customizing field mappings for ModelSerializer classes.
We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to pip install
the new packages, and change any import paths.
This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release.
+ +"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."
@@ -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.
+ +
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
.
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.
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.
For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the style
block.
Screenshot of the bootswatch 'Cerulean' theme
Screenshot of the bootswatch 'Slate' theme
Better support for autocomplete inputs is planned in future versions.
"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 forPUT
andDELETE
, as well as how to support content types other than form-encoded data. + +
The world can only really be changed one piece at a time. The art is picking that piece.
@@ -505,7 +503,7 @@ pip install -r requirements.txtGitHub'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.
-+
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
@@ -559,6 +557,8 @@ More text... --- + +compat.py
module, and should provide a single common interface that the rest of the codebase can use.
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.
-+
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.
-+
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.
-+
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.
-+
Setting the title
The title that is used in the browsable API is generated from the view class name or function name. Any trailing
@@ -434,7 +432,9 @@View
orViewSet
suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.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.
+ +
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.orgNote 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
andnon_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
andnon_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
@@ -464,6 +462,8 @@ available for Django to use. You should see a message likeLANGUAGES
setting: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 anAccept-Language
header for API clients rather than using language URL prefixes.
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:
- Code snippets are always associated with a creator.
@@ -544,7 +542,7 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
Authenticating with the API
-Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication
and BasicAuthentication
.
+Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication
and BasicAuthentication
.
When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.
If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.
If we try to create a snippet without authenticating, we'll get an error:
@@ -569,7 +567,9 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
Summary
We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
-In part 5 of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
+In part 5 of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
+
+
@@ -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](../../../img/quickstart.png)
+![Quick start image](../../img/quickstart.png)
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
+
+