diff options
| author | Tom Christie | 2012-09-01 20:26:27 +0100 | 
|---|---|---|
| committer | Tom Christie | 2012-09-01 20:26:27 +0100 | 
| commit | deedf6957d14c2808c00a009ac2c1d4528cb80c9 (patch) | |
| tree | a029d40c05ceeaffa9d1fb420096c7de4878cbb5 /docs/api-guide | |
| parent | 02dcdca13b7cbe89e1980bab7e8274500bf9e4e1 (diff) | |
| download | django-rest-framework-deedf6957d14c2808c00a009ac2c1d4528cb80c9.tar.bz2 | |
REST framework 2 docs
Diffstat (limited to 'docs/api-guide')
| -rw-r--r-- | docs/api-guide/contentnegotiation.md | 1 | ||||
| -rw-r--r-- | docs/api-guide/exceptions.md | 3 | ||||
| -rw-r--r-- | docs/api-guide/parsers.md | 3 | ||||
| -rw-r--r-- | docs/api-guide/renderers.md | 4 | ||||
| -rw-r--r-- | docs/api-guide/requests.md | 66 | ||||
| -rw-r--r-- | docs/api-guide/responses.md | 23 | ||||
| -rw-r--r-- | docs/api-guide/serializers.md | 241 | ||||
| -rw-r--r-- | docs/api-guide/status-codes.md | 93 | ||||
| -rw-r--r-- | docs/api-guide/urls.md | 41 | ||||
| -rw-r--r-- | docs/api-guide/views.md | 39 | 
10 files changed, 514 insertions, 0 deletions
| diff --git a/docs/api-guide/contentnegotiation.md b/docs/api-guide/contentnegotiation.md new file mode 100644 index 00000000..f01627d8 --- /dev/null +++ b/docs/api-guide/contentnegotiation.md @@ -0,0 +1 @@ +> 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. diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md new file mode 100644 index 00000000..d41327c6 --- /dev/null +++ b/docs/api-guide/exceptions.md @@ -0,0 +1,3 @@ +# Exceptions + + diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md new file mode 100644 index 00000000..2edc11de --- /dev/null +++ b/docs/api-guide/parsers.md @@ -0,0 +1,3 @@ +# Parsers + +## .parse(request) diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md new file mode 100644 index 00000000..5a66da69 --- /dev/null +++ b/docs/api-guide/renderers.md @@ -0,0 +1,4 @@ +# Renderers + +## .render(response) + diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md new file mode 100644 index 00000000..67ddfdac --- /dev/null +++ b/docs/api-guide/requests.md @@ -0,0 +1,66 @@ +# Requests + +> If you're doing REST-based web service stuff ... you should ignore request.POST. +> +> — Malcom Tredinnick, [Django developers group][cite] + +REST framework's `Request` class extends the standard `HttpRequest`, adding support for parsing multiple content types, allowing browser-based `PUT`, `DELETE` and other methods, and adding flexible per-request authentication. + +## .method + +`request.method` returns the uppercased string representation of the request's HTTP method. + +Browser-based `PUT`, `DELETE` and other requests are supported, and can be made by using a hidden form field named `_method` in a regular `POST` form. + + + +## .content_type + +`request.content`, returns a string object representing the mimetype of the HTTP request's body, if one exists. + + + +## .DATA + +`request.DATA` returns the parsed content of the request body.  This is similar to the standard `HttpRequest.POST` attribute except that: + +1. It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests. +2. It supports parsing multiple content types, rather than just form data.  For example you can handle incoming json data in the same way that you handle incoming form data. + +## .FILES + +`request.FILES` returns any uploaded files that may be present in the content of the request body.  This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing that is used for `request.DATA`. + +This allows you to support file uploads from multiple content-types.  For example you can write a parser that supports `POST`ing the raw content of a file, instead of using form-encoded file uploads. + +## .user + +`request.user` returns a `django.contrib.auth.models.User` instance.  + +## .auth + +`request.auth` returns any additional authentication context that may not be contained in `request.user`.  The exact behavior of `request.auth` depends on what authentication has been set in `request.authentication`.  For many types of authentication this will simply be `None`, but it may also be an object representing a permission scope, an expiry time, or any other information that might be contained in a token-based authentication scheme. + +## .parsers + +`request.parsers` should be set to a list of `Parser` instances that can be used to parse the content of the request body. + +`request.parsers` may no longer be altered once `request.DATA`, `request.FILES` or `request.POST` have been accessed. + +If you're using the `djangorestframework.views.View` class... **[TODO]** + +## .stream + +`request.stream` returns a stream representing the content of the request body. + +You will not typically need to access `request.stream`, unless you're writing a `Parser` class. + +## .authentication + +`request.authentication` should be set to a list of `Authentication` instances that can be used to authenticate the request. + +`request.authentication` may no longer be altered once `request.user` or `request.auth` have been accessed. + +If you're using the `djangorestframework.views.View` class... **[TODO]** + +[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
\ No newline at end of file diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md new file mode 100644 index 00000000..38f6e8cb --- /dev/null +++ b/docs/api-guide/responses.md @@ -0,0 +1,23 @@ +# 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][cite] + +REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request. + +The `Response` class subclasses Django's `TemplateResponse`.  `Response` objects are initialised with content, which should consist of native python primatives.  REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. + +There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it does provide a better interface for returning Web API responses. + +## Response(content, headers=None,  renderers=None, view=None, format=None, status=None) + + +## .renderers + +## .view + +## .format + + +[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/
\ No newline at end of file diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md new file mode 100644 index 00000000..377b0c10 --- /dev/null +++ b/docs/api-guide/serializers.md @@ -0,0 +1,241 @@ +# Serializers + +> Expanding the usefulness of the serializers is something that we would +like to address. However, it's not a trivial problem, and it +will take some serious design work. Any offers to help out in this +area would be gratefully accepted. +> +> — Russell Keith-Magee, [Django users group][cite] + +Serializers allow complex data such as querysets and model instances to be converted to native python datatypes that can then be easily rendered into `JSON`, `XML` or other content types.  Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. + +REST framework's serializers work very similarly to Django's `Form` and `ModelForm` classes.  It provides a `Serializer` class which gives you a powerful, generic way to control the output of your responses, as well as a `ModelSerializer` class which provides a useful shortcut for creating serializers that deal with model instances and querysets. + +## Declaring Serializers + +Let's start by creating a simple object we can use for example purposes: + +    class Comment(object): +        def __init__(self, email, content, created=None): +            self.email = email +            self.content = content +            self.created = created or datetime.datetime.now() +     +    comment = Comment(email='leila@example.com', content='foo bar') + +We'll declare a serializer that we can use to serialize and deserialize `Comment` objects. +Declaring a serializer looks very similar to declaring a form: + +    class CommentSerializer(serializers.Serializer): +        email = serializers.EmailField() +        content = serializers.CharField(max_length=200) +        created = serializers.DateTimeField() + +        def restore_object(self, attrs, instance=None): +            if instance: +                instance.title = attrs['title'] +                instance.content = attrs['content'] +                instance.created = attrs['created'] +                return instance +            return Comment(**attrs)  + +The first part of serializer class defines the fields that get serialized/deserialized.  The `restore_object` method defines how fully fledged instances get created when deserializing data.  The `restore_object` method is optional, and is only required if we want our serializer to support deserialization. + +## Serializing objects + +We can now use `CommentSerializer` to serialize a comment, or list of comments.  Again, using the `Serializer` class looks a lot like using a `Form` class. + +    serializer = CommentSerializer(instance=comment) +    serializer.data +    # {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)} + +At this point we've translated the model instance into python native datatypes.  To finalise the serialization process we render the data into `json`. + +    stream = JSONRenderer().render(data) +    stream +    # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}' + +## Deserializing objects +         +Deserialization is similar.  First we parse a stream into python native datatypes...  + +    data = JSONParser().parse(stream) + +...then we restore those native datatypes into a fully populated object instance. + +    serializer = CommentSerializer(data) +    serializer.is_valid() +    # True +    serializer.object +    # <Comment object at 0x10633b2d0> +    >>> serializer.deserialize('json', stream) + +## Validation + +When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object.  If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages. + +**TODO: Describe validation in more depth** + +## Dealing with nested objects + +The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, +where some of the attributes of an object might not be simple datatypes such as strings, dates or integers. + +The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another. + +    class UserSerializer(serializers.Serializer): +        email = serializers.EmailField() +        username = serializers.CharField() +         +        def restore_object(self, attrs, instance=None): +            return User(**attrs) + + +    class CommentSerializer(serializers.Serializer): +        user = serializers.UserSerializer() +        title = serializers.CharField() +        content = serializers.CharField(max_length=200) +        created = serializers.DateTimeField() +         +        def restore_object(self, attrs, instance=None): +            return Comment(**attrs) + +## Creating custom fields + +If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods.  These two methods are used to convert between the intial datatype, and a primative, serializable datatype.  Primative datatypes may be any of a number, string, date/time/datetime or None.  They may also be any list or dictionary like object that only contains other primative objects. + +The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype.  The `from_native()` method is called to restore a primative datatype into it's initial representation. + +Let's look at an example of serializing a class that represents an RGB color value: + +    class Color(object): +        """ +        A color represented in the RGB colorspace. +        """ + +        def __init__(self, red, green, blue): +            assert(red >= 0 and green >= 0 and blue >= 0) +            assert(red < 256 and green < 256 and blue < 256) +            self.red, self.green, self.blue = red, green, blue + +    class ColourField(Field): +        """ +        Color objects are serialized into "rgb(#, #, #)" notation. +        """ + +        def to_native(self, obj): +            return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue) +       +        def from_native(self, data): +            data = data.strip('rgb(').rstrip(')') +            red, green, blue = [int(col) for col in data.split(',')] +            return Color(red, green, blue) +             + +By default field values are treated as mapping to an attribute on the object.  If you need to customize how the field value is accessed and set you need to override `.field_to_native()` and/or `.field_from_native()`. + +As an example, let's create a field that can be used represent the class name of the object being serialized: + +    class ClassNameField(Field): +        def field_to_native(self, obj, field_name): +            """ +            Serialize the object's class name, not an attribute of the object. +            """ +            return obj.__class__.__name__ + +        def field_from_native(self, data, field_name, into): +            """ +            We don't want to set anything when we revert this field. +            """ +            pass + +--- + +# ModelSerializers + +Often you'll want serializer classes that map closely to model definitions. +The `ModelSerializer` class lets you automatically create a Serializer class with fields that corrospond to the Model fields. + +    class AccountSerializer(ModelSerializer): +        class Meta: +            model = Account + +**[TODO: Explain model field to serializer field mapping in more detail]** + +## Specifying fields explicitly  + +You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class. + +    class AccountSerializer(ModelSerializer): +        url = CharField(source='get_absolute_url', readonly=True) +        group = NaturalKeyField() + +        class Meta: +            model = Account + +Extra fields can corrospond to any property or callable on the model. + +## Relational fields + +When serializing model instances, there are a number of different ways you might choose to represent relationships.  The default representation is to use the primary keys of the related instances. + +Alternative representations include serializing using natural keys, serializing complete nested representations, or serializing using a custom representation, such as a URL that uniquely identifies the model instances. + +The `PrimaryKeyField` and `NaturalKeyField` fields provide alternative flat representations. + +The `ModelSerializer` class can itself be used as a field, in order to serialize relationships using nested representations. + +The `RelatedField` class may be subclassed to create a custom represenation of a relationship.  The subclass should override `.to_native()`, and optionally `.from_native()` if deserialization is supported. + +All the relational fields may be used for any relationship or reverse relationship on a model. + +## Specifying which fields should be included + +If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`. + +For example: + +    class AccountSerializer(ModelSerializer): +        class Meta: +            model = Account +            exclude = ('id',) + +The `fields` and `exclude` options may also be set by passing them to the `serialize()` method. + +**[TODO: Possibly only allow .serialize(fields=…) in FixtureSerializer for backwards compatability, but remove for ModelSerializer]** + +## Specifiying nested serialization + +The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `nested` option: + +    class AccountSerializer(ModelSerializer): +        class Meta: +            model = Account +            exclude = ('id',) +            nested = True + +The `nested` option may be set to either `True`, `False`, or an integer value.  If given an integer value it indicates the depth of relationships that should be traversed before reverting to a flat representation. + +When serializing objects using a nested representation any occurances of recursion will be recognised, and will fall back to using a flat representation. + +The `nested` option may also be set by passing it to the `serialize()` method. + +**[TODO: Possibly only allow .serialize(nested=…) in FixtureSerializer]** + +## Customising the default fields used by a ModelSerializer + +    class AccountSerializer(ModelSerializer): +        class Meta: +            model = Account + +        def get_nested_field(self, model_field): +            return ModelSerializer() + +        def get_related_field(self, model_field): +            return NaturalKeyField() + +        def get_field(self, model_field): +            return Field() + + +[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md new file mode 100644 index 00000000..c1d45905 --- /dev/null +++ b/docs/api-guide/status-codes.md @@ -0,0 +1,93 @@ +# 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][rfc2324], Hyper Text Coffee Pot Control Protocol + +Using bare status codes in your responses isn't recommended.  REST framework includes a set of named constants that you can use to make more code more obvious and readable. + +    from djangorestframework import status + +    def empty_view(self): +        content = {'please move along': 'nothing to see here'} +        return Response(content, status=status.HTTP_404_NOT_FOUND) + +The full set of HTTP status codes included in the `status` module is listed below. + +For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616] +and [RFC 6585][rfc6585]. + +## Informational - 1xx + +This class of status code indicates a provisional response.  There are no 1xx status codes used in REST framework by default. + +    HTTP_100_CONTINUE +    HTTP_101_SWITCHING_PROTOCOLS + +## Successful - 2xx + +This class of status code indicates that the client's request was successfully received, understood, and accepted. + +    HTTP_200_OK +    HTTP_201_CREATED +    HTTP_202_ACCEPTED +    HTTP_203_NON_AUTHORITATIVE_INFORMATION +    HTTP_204_NO_CONTENT +    HTTP_205_RESET_CONTENT +    HTTP_206_PARTIAL_CONTENT + +## Redirection - 3xx  + +This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. + +    HTTP_300_MULTIPLE_CHOICES +    HTTP_301_MOVED_PERMANENTLY +    HTTP_302_FOUND +    HTTP_303_SEE_OTHER +    HTTP_304_NOT_MODIFIED +    HTTP_305_USE_PROXY +    HTTP_306_RESERVED +    HTTP_307_TEMPORARY_REDIRECT + +## Client Error - 4xx + +The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. + +    HTTP_400_BAD_REQUEST +    HTTP_401_UNAUTHORIZED +    HTTP_402_PAYMENT_REQUIRED +    HTTP_403_FORBIDDEN +    HTTP_404_NOT_FOUND +    HTTP_405_METHOD_NOT_ALLOWED +    HTTP_406_NOT_ACCEPTABLE +    HTTP_407_PROXY_AUTHENTICATION_REQUIRED +    HTTP_408_REQUEST_TIMEOUT +    HTTP_409_CONFLICT +    HTTP_410_GONE +    HTTP_411_LENGTH_REQUIRED +    HTTP_412_PRECONDITION_FAILED +    HTTP_413_REQUEST_ENTITY_TOO_LARGE +    HTTP_414_REQUEST_URI_TOO_LONG +    HTTP_415_UNSUPPORTED_MEDIA_TYPE +    HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE +    HTTP_417_EXPECTATION_FAILED +    HTTP_428_PRECONDITION_REQUIRED +    HTTP_429_TOO_MANY_REQUESTS +    HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE + +## Server Error - 5xx + +Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. + +    HTTP_500_INTERNAL_SERVER_ERROR +    HTTP_501_NOT_IMPLEMENTED +    HTTP_502_BAD_GATEWAY +    HTTP_503_SERVICE_UNAVAILABLE +    HTTP_504_GATEWAY_TIMEOUT +    HTTP_505_HTTP_VERSION_NOT_SUPPORTED +    HTTP_511_NETWORD_AUTHENTICATION_REQUIRED + + +[rfc2324]: http://www.ietf.org/rfc/rfc2324.txt +[rfc2616]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html +[rfc6585]: http://tools.ietf.org/html/rfc6585 diff --git a/docs/api-guide/urls.md b/docs/api-guide/urls.md new file mode 100644 index 00000000..c39ff8f6 --- /dev/null +++ b/docs/api-guide/urls.md @@ -0,0 +1,41 @@ +# Returning URIs from your Web APIs + +> 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][cite] + +As a rule, it's probably better practice to return absolute URIs from you web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`. + +The advantages of doing so are: + +* It's more explicit. +* It leaves less work for your API clients. +* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type. +* It allows use to easily do things like markup HTML representations with hyperlinks. + +REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API. + +There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier. + +## reverse(viewname, request, *args, **kwargs) + +Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port. + +    from djangorestframework.utils import reverse +    from djangorestframework.views import APIView +    +	class MyView(APIView): +	    def get(self, request): +			content = { + 				... +    		    'url': reverse('year-summary', request, args=[1945]) +            } +    		return Response(content) + +## reverse_lazy(viewname, request, *args, **kwargs) + +Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port. + +[cite]: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5 +[reverse]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse +[reverse-lazy]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
\ No newline at end of file diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md new file mode 100644 index 00000000..dd1dbebe --- /dev/null +++ b/docs/api-guide/views.md @@ -0,0 +1,39 @@ +> Django's class based views are a welcome departure from the old-style views. +> +> — [Reinout van Rees][cite] + +# Views + +REST framework provides a simple `APIView` class, built on Django's `django.generics.views.View`.  The `APIView` class ensures five main things: + +1. Any requests inside the view will become `Request` instances. +2. `Request` instances will have their `renderers` and `authentication` attributes automatically set.  +3. `Response` instances will have their `parsers` and `serializer` attributes automatically set. +4. `APIException` exceptions will be caught and return appropriate responses. +5. Any permissions provided will be checked prior to passing the request to a handler method. + +Additionally there are a some minor extras, such as providing a default `options` handler, setting some common headers on the response prior to return, and providing the useful `initial()` and `final()` hooks. + +## APIView + +## Method handlers + +Describe that APIView handles regular .get(), .post(), .put(), .delete() etc... + +## .initial(request, *args, **kwargs) + +## .final(request, response, *args, **kwargs) + +## .parsers + +## .renderers + +## .serializer + +## .authentication + +## .permissions + +## .headers + +[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
\ No newline at end of file | 
