mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-10-22 11:44:35 +03:00
Deployed c0f3649
with MkDocs version: 1.6.0
This commit is contained in:
parent
5031b247cb
commit
fedcbc3126
File diff suppressed because one or more lines are too long
140
sitemap.xml
140
sitemap.xml
|
@ -2,352 +2,352 @@
|
|||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/authentication/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/caching/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/content-negotiation/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/exceptions/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/fields/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/filtering/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/format-suffixes/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/generic-views/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/metadata/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/pagination/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/parsers/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/permissions/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/relations/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/renderers/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/requests/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/responses/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/reverse/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/routers/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/schemas/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/serializers/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/settings/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/status-codes/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/testing/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/throttling/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/validators/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/versioning/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/views/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/api-guide/viewsets/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.0-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.1-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.10-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.11-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.12-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.13-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.14-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.15-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.16-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.2-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.3-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.4-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.5-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.6-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.7-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.8-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/3.9-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/contributing/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/funding/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/jobs/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/kickstarter-announcement/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/mozilla-grant/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/project-management/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/release-notes/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/third-party-packages/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/community/tutorials-and-resources/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/topics/ajax-csrf-cors/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/topics/browsable-api/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/topics/browser-enhancements/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/topics/documenting-your-api/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/topics/html-and-forms/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/topics/internationalization/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/topics/rest-hypermedia-hateoas/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/topics/writable-nested-serializers/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/tutorial/1-serialization/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/tutorial/2-requests-and-responses/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/tutorial/3-class-based-views/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://www.django-rest-framework.org/tutorial/quickstart/</loc>
|
||||
<lastmod>2025-10-09</lastmod>
|
||||
<lastmod>2025-10-14</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
</urlset>
|
BIN
sitemap.xml.gz
BIN
sitemap.xml.gz
Binary file not shown.
|
@ -485,11 +485,11 @@
|
|||
<hr />
|
||||
<h2 id="setting-up-a-new-environment"><a class="toclink" href="#setting-up-a-new-environment">Setting up a new environment</a></h2>
|
||||
<p>Before we do anything else we'll create a new virtual environment, using <a href="https://docs.python.org/3/library/venv.html">venv</a>. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.</p>
|
||||
<pre><code>python3 -m venv env
|
||||
<pre><code class="language-bash">python3 -m venv env
|
||||
source env/bin/activate
|
||||
</code></pre>
|
||||
<p>Now that we're inside a virtual environment, we can install our package requirements.</p>
|
||||
<pre><code>pip install django
|
||||
<pre><code class="language-bash">pip install django
|
||||
pip install djangorestframework
|
||||
pip install pygments # We'll be using this for the code highlighting
|
||||
</code></pre>
|
||||
|
@ -497,15 +497,15 @@ pip install pygments # We'll be using this for the code highlighting
|
|||
<h2 id="getting-started"><a class="toclink" href="#getting-started">Getting started</a></h2>
|
||||
<p>Okay, we're ready to get coding.
|
||||
To get started, let's create a new project to work with.</p>
|
||||
<pre><code>cd ~
|
||||
<pre><code class="language-bash">cd ~
|
||||
django-admin startproject tutorial
|
||||
cd tutorial
|
||||
</code></pre>
|
||||
<p>Once that's done we can create an app that we'll use to create a simple Web API.</p>
|
||||
<pre><code>python manage.py startapp snippets
|
||||
<pre><code class="language-bash">python manage.py startapp snippets
|
||||
</code></pre>
|
||||
<p>We'll need to add our new <code>snippets</code> app and the <code>rest_framework</code> app to <code>INSTALLED_APPS</code>. Let's edit the <code>tutorial/settings.py</code> file:</p>
|
||||
<pre><code>INSTALLED_APPS = [
|
||||
<pre><code class="language-text">INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
'snippets',
|
||||
|
@ -514,7 +514,7 @@ cd tutorial
|
|||
<p>Okay, we're ready to roll.</p>
|
||||
<h2 id="creating-a-model-to-work-with"><a class="toclink" href="#creating-a-model-to-work-with">Creating a model to work with</a></h2>
|
||||
<p>For the purposes of this tutorial we're going to start by creating a simple <code>Snippet</code> model that is used to store code snippets. Go ahead and edit the <code>snippets/models.py</code> file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.</p>
|
||||
<pre><code>from django.db import models
|
||||
<pre><code class="language-python">from django.db import models
|
||||
from pygments.lexers import get_all_lexers
|
||||
from pygments.styles import get_all_styles
|
||||
|
||||
|
@ -525,48 +525,50 @@ STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
|
|||
|
||||
class Snippet(models.Model):
|
||||
created = models.DateTimeField(auto_now_add=True)
|
||||
title = models.CharField(max_length=100, blank=True, default='')
|
||||
title = models.CharField(max_length=100, blank=True, default="")
|
||||
code = models.TextField()
|
||||
linenos = models.BooleanField(default=False)
|
||||
language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
|
||||
style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)
|
||||
language = models.CharField(
|
||||
choices=LANGUAGE_CHOICES, default="python", max_length=100
|
||||
)
|
||||
style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100)
|
||||
|
||||
class Meta:
|
||||
ordering = ['created']
|
||||
ordering = ["created"]
|
||||
</code></pre>
|
||||
<p>We'll also need to create an initial migration for our snippet model, and sync the database for the first time.</p>
|
||||
<pre><code>python manage.py makemigrations snippets
|
||||
<pre><code class="language-bash">python manage.py makemigrations snippets
|
||||
python manage.py migrate snippets
|
||||
</code></pre>
|
||||
<h2 id="creating-a-serializer-class"><a class="toclink" href="#creating-a-serializer-class">Creating a Serializer class</a></h2>
|
||||
<p>The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as <code>json</code>. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the <code>snippets</code> directory named <code>serializers.py</code> and add the following.</p>
|
||||
<pre><code>from rest_framework import serializers
|
||||
<pre><code class="language-python">from rest_framework import serializers
|
||||
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
|
||||
|
||||
|
||||
class SnippetSerializer(serializers.Serializer):
|
||||
id = serializers.IntegerField(read_only=True)
|
||||
title = serializers.CharField(required=False, allow_blank=True, max_length=100)
|
||||
code = serializers.CharField(style={'base_template': 'textarea.html'})
|
||||
code = serializers.CharField(style={"base_template": "textarea.html"})
|
||||
linenos = serializers.BooleanField(required=False)
|
||||
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
|
||||
style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')
|
||||
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default="python")
|
||||
style = serializers.ChoiceField(choices=STYLE_CHOICES, default="friendly")
|
||||
|
||||
def create(self, validated_data):
|
||||
"""
|
||||
"""
|
||||
Create and return a new `Snippet` instance, given the validated data.
|
||||
"""
|
||||
"""
|
||||
return Snippet.objects.create(**validated_data)
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
"""
|
||||
"""
|
||||
Update and return an existing `Snippet` instance, given the validated data.
|
||||
"""
|
||||
instance.title = validated_data.get('title', instance.title)
|
||||
instance.code = validated_data.get('code', instance.code)
|
||||
instance.linenos = validated_data.get('linenos', instance.linenos)
|
||||
instance.language = validated_data.get('language', instance.language)
|
||||
instance.style = validated_data.get('style', instance.style)
|
||||
"""
|
||||
instance.title = validated_data.get("title", instance.title)
|
||||
instance.code = validated_data.get("code", instance.code)
|
||||
instance.linenos = validated_data.get("linenos", instance.linenos)
|
||||
instance.language = validated_data.get("language", instance.language)
|
||||
instance.style = validated_data.get("style", instance.style)
|
||||
instance.save()
|
||||
return instance
|
||||
</code></pre>
|
||||
|
@ -576,72 +578,73 @@ class SnippetSerializer(serializers.Serializer):
|
|||
<p>We can actually also save ourselves some time by using the <code>ModelSerializer</code> class, as we'll see later, but for now we'll keep our serializer definition explicit.</p>
|
||||
<h2 id="working-with-serializers"><a class="toclink" href="#working-with-serializers">Working with Serializers</a></h2>
|
||||
<p>Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell.</p>
|
||||
<pre><code>python manage.py shell
|
||||
<pre><code class="language-bash">python manage.py shell
|
||||
</code></pre>
|
||||
<p>Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.</p>
|
||||
<pre><code>from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
from rest_framework.renderers import JSONRenderer
|
||||
from rest_framework.parsers import JSONParser
|
||||
<pre><code class="language-pycon">>>> from snippets.models import Snippet
|
||||
>>> from snippets.serializers import SnippetSerializer
|
||||
>>> from rest_framework.renderers import JSONRenderer
|
||||
>>> from rest_framework.parsers import JSONParser
|
||||
|
||||
snippet = Snippet(code='foo = "bar"\n')
|
||||
snippet.save()
|
||||
>>> snippet = Snippet(code='foo = "bar"\n')
|
||||
>>> snippet.save()
|
||||
|
||||
snippet = Snippet(code='print("hello, world")\n')
|
||||
snippet.save()
|
||||
>>> snippet = Snippet(code='print("hello, world")\n')
|
||||
>>> snippet.save()
|
||||
</code></pre>
|
||||
<p>We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.</p>
|
||||
<pre><code>serializer = SnippetSerializer(snippet)
|
||||
serializer.data
|
||||
# {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
|
||||
<pre><code class="language-pycon">>>> serializer = SnippetSerializer(snippet)
|
||||
>>> serializer.data
|
||||
{'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
|
||||
</code></pre>
|
||||
<p>At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into <code>json</code>.</p>
|
||||
<pre><code>content = JSONRenderer().render(serializer.data)
|
||||
content
|
||||
# b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'
|
||||
<pre><code class="language-pycon">>>> content = JSONRenderer().render(serializer.data)
|
||||
>>> content
|
||||
b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'
|
||||
</code></pre>
|
||||
<p>Deserialization is similar. First we parse a stream into Python native datatypes...</p>
|
||||
<pre><code>import io
|
||||
<pre><code class="language-pycon">>>> import io
|
||||
|
||||
stream = io.BytesIO(content)
|
||||
data = JSONParser().parse(stream)
|
||||
>>> stream = io.BytesIO(content)
|
||||
>>> data = JSONParser().parse(stream)
|
||||
</code></pre>
|
||||
<p>...then we restore those native datatypes into a fully populated object instance.</p>
|
||||
<pre><code>serializer = SnippetSerializer(data=data)
|
||||
serializer.is_valid()
|
||||
# True
|
||||
serializer.validated_data
|
||||
# {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
|
||||
serializer.save()
|
||||
# <Snippet: Snippet object>
|
||||
<pre><code class="language-pycon">>>> serializer = SnippetSerializer(data=data)
|
||||
>>> serializer.is_valid()
|
||||
True
|
||||
>>> serializer.validated_data
|
||||
{'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
|
||||
>>> serializer.save()
|
||||
<Snippet: Snippet object>
|
||||
</code></pre>
|
||||
<p>Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.</p>
|
||||
<p>We can also serialize querysets instead of model instances. To do so we simply add a <code>many=True</code> flag to the serializer arguments.</p>
|
||||
<pre><code>serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
||||
serializer.data
|
||||
# [{'id': 1, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]
|
||||
<pre><code class="language-pycon">>>> serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
||||
>>> serializer.data
|
||||
[{'id': 1, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]
|
||||
</code></pre>
|
||||
<h2 id="using-modelserializers"><a class="toclink" href="#using-modelserializers">Using ModelSerializers</a></h2>
|
||||
<p>Our <code>SnippetSerializer</code> class is replicating a lot of information that's also contained in the <code>Snippet</code> model. It would be nice if we could keep our code a bit more concise.</p>
|
||||
<p>In the same way that Django provides both <code>Form</code> classes and <code>ModelForm</code> classes, REST framework includes both <code>Serializer</code> classes, and <code>ModelSerializer</code> classes.</p>
|
||||
<p>Let's look at refactoring our serializer using the <code>ModelSerializer</code> class.
|
||||
Open the file <code>snippets/serializers.py</code> again, and replace the <code>SnippetSerializer</code> class with the following.</p>
|
||||
<pre><code>class SnippetSerializer(serializers.ModelSerializer):
|
||||
<pre><code class="language-python">class SnippetSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Snippet
|
||||
fields = ['id', 'title', 'code', 'linenos', 'language', 'style']
|
||||
fields = ["id", "title", "code", "linenos", "language", "style"]
|
||||
</code></pre>
|
||||
<p>One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with <code>python manage.py shell</code>, then try the following:</p>
|
||||
<pre><code>from snippets.serializers import SnippetSerializer
|
||||
serializer = SnippetSerializer()
|
||||
print(repr(serializer))
|
||||
# SnippetSerializer():
|
||||
# id = IntegerField(label='ID', read_only=True)
|
||||
# title = CharField(allow_blank=True, max_length=100, required=False)
|
||||
# code = CharField(style={'base_template': 'textarea.html'})
|
||||
# linenos = BooleanField(required=False)
|
||||
# language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
|
||||
# style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
|
||||
<pre><code class="language-pycon">>>> from snippets.serializers import SnippetSerializer
|
||||
|
||||
>>> serializer = SnippetSerializer()
|
||||
>>> print(repr(serializer))
|
||||
SnippetSerializer():
|
||||
id = IntegerField(label='ID', read_only=True)
|
||||
title = CharField(allow_blank=True, max_length=100, required=False)
|
||||
code = CharField(style={'base_template': 'textarea.html'})
|
||||
linenos = BooleanField(required=False)
|
||||
language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
|
||||
style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
|
||||
</code></pre>
|
||||
<p>It's important to remember that <code>ModelSerializer</code> classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:</p>
|
||||
<ul>
|
||||
|
@ -652,24 +655,24 @@ print(repr(serializer))
|
|||
<p>Let's see how we can write some API views using our new Serializer class.
|
||||
For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.</p>
|
||||
<p>Edit the <code>snippets/views.py</code> file, and add the following.</p>
|
||||
<pre><code>from django.http import HttpResponse, JsonResponse
|
||||
<pre><code class="language-python">from django.http import HttpResponse, JsonResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from rest_framework.parsers import JSONParser
|
||||
from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
</code></pre>
|
||||
<p>The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.</p>
|
||||
<pre><code>@csrf_exempt
|
||||
<pre><code class="language-python">@csrf_exempt
|
||||
def snippet_list(request):
|
||||
"""
|
||||
"""
|
||||
List all code snippets, or create a new snippet.
|
||||
"""
|
||||
if request.method == 'GET':
|
||||
"""
|
||||
if request.method == "GET":
|
||||
snippets = Snippet.objects.all()
|
||||
serializer = SnippetSerializer(snippets, many=True)
|
||||
return JsonResponse(serializer.data, safe=False)
|
||||
|
||||
elif request.method == 'POST':
|
||||
elif request.method == "POST":
|
||||
data = JSONParser().parse(request)
|
||||
serializer = SnippetSerializer(data=data)
|
||||
if serializer.is_valid():
|
||||
|
@ -679,21 +682,21 @@ def snippet_list(request):
|
|||
</code></pre>
|
||||
<p>Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as <code>csrf_exempt</code>. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.</p>
|
||||
<p>We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.</p>
|
||||
<pre><code>@csrf_exempt
|
||||
<pre><code class="language-python">@csrf_exempt
|
||||
def snippet_detail(request, pk):
|
||||
"""
|
||||
"""
|
||||
Retrieve, update or delete a code snippet.
|
||||
"""
|
||||
"""
|
||||
try:
|
||||
snippet = Snippet.objects.get(pk=pk)
|
||||
except Snippet.DoesNotExist:
|
||||
return HttpResponse(status=404)
|
||||
|
||||
if request.method == 'GET':
|
||||
if request.method == "GET":
|
||||
serializer = SnippetSerializer(snippet)
|
||||
return JsonResponse(serializer.data)
|
||||
|
||||
elif request.method == 'PUT':
|
||||
elif request.method == "PUT":
|
||||
data = JSONParser().parse(request)
|
||||
serializer = SnippetSerializer(snippet, data=data)
|
||||
if serializer.is_valid():
|
||||
|
@ -701,34 +704,34 @@ def snippet_detail(request, pk):
|
|||
return JsonResponse(serializer.data)
|
||||
return JsonResponse(serializer.errors, status=400)
|
||||
|
||||
elif request.method == 'DELETE':
|
||||
elif request.method == "DELETE":
|
||||
snippet.delete()
|
||||
return HttpResponse(status=204)
|
||||
</code></pre>
|
||||
<p>Finally we need to wire these views up. Create the <code>snippets/urls.py</code> file:</p>
|
||||
<pre><code>from django.urls import path
|
||||
<pre><code class="language-python">from django.urls import path
|
||||
from snippets import views
|
||||
|
||||
urlpatterns = [
|
||||
path('snippets/', views.snippet_list),
|
||||
path('snippets/<int:pk>/', views.snippet_detail),
|
||||
path("snippets/", views.snippet_list),
|
||||
path("snippets/<int:pk>/", views.snippet_detail),
|
||||
]
|
||||
</code></pre>
|
||||
<p>We also need to wire up the root urlconf, in the <code>tutorial/urls.py</code> file, to include our snippet app's URLs.</p>
|
||||
<pre><code>from django.urls import path, include
|
||||
<pre><code class="language-python">from django.urls import path, include
|
||||
|
||||
urlpatterns = [
|
||||
path('', include('snippets.urls')),
|
||||
path("", include("snippets.urls")),
|
||||
]
|
||||
</code></pre>
|
||||
<p>It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed <code>json</code>, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.</p>
|
||||
<h2 id="testing-our-first-attempt-at-a-web-api"><a class="toclink" href="#testing-our-first-attempt-at-a-web-api">Testing our first attempt at a Web API</a></h2>
|
||||
<p>Now we can start up a sample server that serves our snippets.</p>
|
||||
<p>Quit out of the shell...</p>
|
||||
<pre><code>quit()
|
||||
<pre><code class="language-pycon">>>> quit()
|
||||
</code></pre>
|
||||
<p>...and start up Django's development server.</p>
|
||||
<pre><code>python manage.py runserver
|
||||
<pre><code class="language-bash">python manage.py runserver
|
||||
|
||||
Validating models...
|
||||
|
||||
|
@ -740,52 +743,52 @@ Quit the server with CONTROL-C.
|
|||
<p>In another terminal window, we can test the server.</p>
|
||||
<p>We can test our API using <a href="https://curl.haxx.se/">curl</a> or <a href="https://github.com/httpie/httpie#installation">httpie</a>. Httpie is a user friendly http client that's written in Python. Let's install that.</p>
|
||||
<p>You can install httpie using pip:</p>
|
||||
<pre><code>pip install httpie
|
||||
<pre><code class="language-bash">pip install httpie
|
||||
</code></pre>
|
||||
<p>Finally, we can get a list of all of the snippets:</p>
|
||||
<pre><code>http GET http://127.0.0.1:8000/snippets/ --unsorted
|
||||
<pre><code class="language-bash">http GET http://127.0.0.1:8000/snippets/ --unsorted
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
...
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"title": "",
|
||||
"code": "foo = \"bar\"\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
"id": 1,
|
||||
"title": "",
|
||||
"code": "foo = \"bar\"\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
"id": 3,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
]
|
||||
</code></pre>
|
||||
<p>Or we can get a particular snippet by referencing its id:</p>
|
||||
<pre><code>http GET http://127.0.0.1:8000/snippets/2/ --unsorted
|
||||
<pre><code class="language-bash">http GET http://127.0.0.1:8000/snippets/2/ --unsorted
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
...
|
||||
{
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
</code></pre>
|
||||
<p>Similarly, you can have the same json displayed by visiting these URLs in a web browser.</p>
|
||||
|
|
|
@ -473,12 +473,12 @@
|
|||
Let's introduce a couple of essential building blocks.</p>
|
||||
<h2 id="request-objects"><a class="toclink" href="#request-objects">Request objects</a></h2>
|
||||
<p>REST framework introduces a <code>Request</code> object that extends the regular <code>HttpRequest</code>, and provides more flexible request parsing. The core functionality of the <code>Request</code> object is the <code>request.data</code> attribute, which is similar to <code>request.POST</code>, but more useful for working with Web APIs.</p>
|
||||
<pre><code>request.POST # Only handles form data. Only works for 'POST' method.
|
||||
<pre><code class="language-python">request.POST # Only handles form data. Only works for 'POST' method.
|
||||
request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
|
||||
</code></pre>
|
||||
<h2 id="response-objects"><a class="toclink" href="#response-objects">Response objects</a></h2>
|
||||
<p>REST framework also introduces a <code>Response</code> object, which is a type of <code>TemplateResponse</code> that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.</p>
|
||||
<pre><code>return Response(data) # Renders to content type as requested by the client.
|
||||
<pre><code class="language-python">return Response(data) # Renders to content type as requested by the client.
|
||||
</code></pre>
|
||||
<h2 id="status-codes"><a class="toclink" href="#status-codes">Status codes</a></h2>
|
||||
<p>Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as <code>HTTP_400_BAD_REQUEST</code> in the <code>status</code> module. It's a good idea to use these throughout rather than using numeric identifiers.</p>
|
||||
|
@ -492,24 +492,24 @@ request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' met
|
|||
<p>The wrappers also provide behavior such as returning <code>405 Method Not Allowed</code> responses when appropriate, and handling any <code>ParseError</code> exceptions that occur when accessing <code>request.data</code> with malformed input.</p>
|
||||
<h2 id="pulling-it-all-together"><a class="toclink" href="#pulling-it-all-together">Pulling it all together</a></h2>
|
||||
<p>Okay, let's go ahead and start using these new components to refactor our views slightly.</p>
|
||||
<pre><code>from rest_framework import status
|
||||
<pre><code class="language-python">from rest_framework import status
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
|
||||
|
||||
@api_view(['GET', 'POST'])
|
||||
@api_view(["GET", "POST"])
|
||||
def snippet_list(request):
|
||||
"""
|
||||
"""
|
||||
List all code snippets, or create a new snippet.
|
||||
"""
|
||||
if request.method == 'GET':
|
||||
"""
|
||||
if request.method == "GET":
|
||||
snippets = Snippet.objects.all()
|
||||
serializer = SnippetSerializer(snippets, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
elif request.method == 'POST':
|
||||
elif request.method == "POST":
|
||||
serializer = SnippetSerializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
|
@ -518,49 +518,47 @@ def snippet_list(request):
|
|||
</code></pre>
|
||||
<p>Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.</p>
|
||||
<p>Here is the view for an individual snippet, in the <code>views.py</code> module.</p>
|
||||
<pre><code>@api_view(['GET', 'PUT', 'DELETE'])
|
||||
<pre><code class="language-python">@api_view(["GET", "PUT", "DELETE"])
|
||||
def snippet_detail(request, pk):
|
||||
"""
|
||||
"""
|
||||
Retrieve, update or delete a code snippet.
|
||||
"""
|
||||
"""
|
||||
try:
|
||||
snippet = Snippet.objects.get(pk=pk)
|
||||
except Snippet.DoesNotExist:
|
||||
return Response(status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
if request.method == 'GET':
|
||||
if request.method == "GET":
|
||||
serializer = SnippetSerializer(snippet)
|
||||
return Response(serializer.data)
|
||||
|
||||
elif request.method == 'PUT':
|
||||
elif request.method == "PUT":
|
||||
serializer = SnippetSerializer(snippet, data=request.data)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
elif request.method == 'DELETE':
|
||||
elif request.method == "DELETE":
|
||||
snippet.delete()
|
||||
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||
</code></pre>
|
||||
<p>This should all feel very familiar - it is not a lot different from working with regular Django views.</p>
|
||||
<p>Notice that we're no longer explicitly tying our requests or responses to a given content type. <code>request.data</code> can handle incoming <code>json</code> requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.</p>
|
||||
<h2 id="adding-optional-format-suffixes-to-our-urls"><a class="toclink" href="#adding-optional-format-suffixes-to-our-urls">Adding optional format suffixes to our URLs</a></h2>
|
||||
<p>To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as <a href="http://example.com/api/items/4.json">http://example.com/api/items/4.json</a>.</p>
|
||||
<p>Start by adding a <code>format</code> keyword argument to both of the views, like so.</p>
|
||||
<pre><code>def snippet_list(request, format=None):
|
||||
</code></pre>
|
||||
<p>and</p>
|
||||
<pre><code>def snippet_detail(request, pk, format=None):
|
||||
</code></pre>
|
||||
<p>To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as <a href="http://example.com/api/items/4.json"><a href="http://example.com/api/items/4.json">http://example.com/api/items/4.json</a></a>.</p>
|
||||
<p>Start by adding a <code>format</code> keyword argument to both of the views, like so.
|
||||
<code>def snippet_list(request, format=None):</code>
|
||||
and
|
||||
<code>def snippet_detail(request, pk, format=None):</code></p>
|
||||
<p>Now update the <code>snippets/urls.py</code> file slightly, to append a set of <code>format_suffix_patterns</code> in addition to the existing URLs.</p>
|
||||
<pre><code>from django.urls import path
|
||||
<pre><code class="language-python">from django.urls import path
|
||||
from rest_framework.urlpatterns import format_suffix_patterns
|
||||
from snippets import views
|
||||
|
||||
urlpatterns = [
|
||||
path('snippets/', views.snippet_list),
|
||||
path('snippets/<int:pk>/', views.snippet_detail),
|
||||
path("snippets/", views.snippet_list),
|
||||
path("snippets/<int:pk>/", views.snippet_detail),
|
||||
]
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||
|
@ -569,64 +567,64 @@ urlpatterns = format_suffix_patterns(urlpatterns)
|
|||
<h2 id="hows-it-looking"><a class="toclink" href="#hows-it-looking">How's it looking?</a></h2>
|
||||
<p>Go ahead and test the API from the command line, as we did in <a href="../1-serialization/">tutorial part 1</a>. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.</p>
|
||||
<p>We can get a list of all of the snippets, as before.</p>
|
||||
<pre><code>http http://127.0.0.1:8000/snippets/
|
||||
<pre><code class="language-bash">http http://127.0.0.1:8000/snippets/
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
...
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"title": "",
|
||||
"code": "foo = \"bar\"\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
{
|
||||
"id": 1,
|
||||
"title": "",
|
||||
"code": "foo = \"bar\"\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
]
|
||||
</code></pre>
|
||||
<p>We can control the format of the response that we get back, either by using the <code>Accept</code> header:</p>
|
||||
<pre><code>http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON
|
||||
<pre><code class="language-bash">http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON
|
||||
http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML
|
||||
</code></pre>
|
||||
<p>Or by appending a format suffix:</p>
|
||||
<pre><code>http http://127.0.0.1:8000/snippets.json # JSON suffix
|
||||
<pre><code class="language-bash">http http://127.0.0.1:8000/snippets.json # JSON suffix
|
||||
http http://127.0.0.1:8000/snippets.api # Browsable API suffix
|
||||
</code></pre>
|
||||
<p>Similarly, we can control the format of the request that we send, using the <code>Content-Type</code> header.</p>
|
||||
<pre><code># POST using form data
|
||||
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
|
||||
<pre><code class="language-bash"># POST using form data
|
||||
http --form POST http://127.0.0.1:8000/snippets/ code="print(123)"
|
||||
|
||||
{
|
||||
"id": 3,
|
||||
"title": "",
|
||||
"code": "print(123)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
"id": 3,
|
||||
"title": "",
|
||||
"code": "print(123)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
|
||||
# POST using JSON
|
||||
http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
|
||||
http --json POST http://127.0.0.1:8000/snippets/ code="print(456)"
|
||||
|
||||
{
|
||||
"id": 4,
|
||||
"title": "",
|
||||
"code": "print(456)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
"id": 4,
|
||||
"title": "",
|
||||
"code": "print(456)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
</code></pre>
|
||||
<p>If you add a <code>--debug</code> switch to the <code>http</code> requests above, you will be able to see the request type in request headers.</p>
|
||||
<p>Now go and open the API in a web browser, by visiting <a href="http://127.0.0.1:8000/snippets/">http://127.0.0.1:8000/snippets/</a>.</p>
|
||||
<p>Now go and open the API in a web browser, by visiting <a href="http://127.0.0.1:8000/snippets/"><a href="http://127.0.0.1:8000/snippets/">http://127.0.0.1:8000/snippets/</a></a>.</p>
|
||||
<h3 id="browsability"><a class="toclink" href="#browsability">Browsability</a></h3>
|
||||
<p>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.</p>
|
||||
<p>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.</p>
|
||||
|
|
|
@ -452,7 +452,7 @@
|
|||
<p>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 <a href="https://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>.</p>
|
||||
<h2 id="rewriting-our-api-using-class-based-views"><a class="toclink" href="#rewriting-our-api-using-class-based-views">Rewriting our API using class-based views</a></h2>
|
||||
<p>We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of <code>views.py</code>.</p>
|
||||
<pre><code>from snippets.models import Snippet
|
||||
<pre><code class="language-python">from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
from django.http import Http404
|
||||
from rest_framework.views import APIView
|
||||
|
@ -461,9 +461,10 @@ from rest_framework import status
|
|||
|
||||
|
||||
class SnippetList(APIView):
|
||||
"""
|
||||
"""
|
||||
List all snippets, or create a new snippet.
|
||||
"""
|
||||
"""
|
||||
|
||||
def get(self, request, format=None):
|
||||
snippets = Snippet.objects.all()
|
||||
serializer = SnippetSerializer(snippets, many=True)
|
||||
|
@ -477,10 +478,11 @@ class SnippetList(APIView):
|
|||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
</code></pre>
|
||||
<p>So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in <code>views.py</code>.</p>
|
||||
<pre><code>class SnippetDetail(APIView):
|
||||
"""
|
||||
<pre><code class="language-python">class SnippetDetail(APIView):
|
||||
"""
|
||||
Retrieve, update or delete a snippet instance.
|
||||
"""
|
||||
"""
|
||||
|
||||
def get_object(self, pk):
|
||||
try:
|
||||
return Snippet.objects.get(pk=pk)
|
||||
|
@ -507,13 +509,13 @@ class SnippetList(APIView):
|
|||
</code></pre>
|
||||
<p>That's looking good. Again, it's still pretty similar to the function based view right now.</p>
|
||||
<p>We'll also need to refactor our <code>snippets/urls.py</code> slightly now that we're using class-based views.</p>
|
||||
<pre><code>from django.urls import path
|
||||
<pre><code class="language-python">from django.urls import path
|
||||
from rest_framework.urlpatterns import format_suffix_patterns
|
||||
from snippets import views
|
||||
|
||||
urlpatterns = [
|
||||
path('snippets/', views.SnippetList.as_view()),
|
||||
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
|
||||
path("snippets/", views.SnippetList.as_view()),
|
||||
path("snippets/<int:pk>/", views.SnippetDetail.as_view()),
|
||||
]
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||
|
@ -523,14 +525,15 @@ urlpatterns = format_suffix_patterns(urlpatterns)
|
|||
<p>One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.</p>
|
||||
<p>The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.</p>
|
||||
<p>Let's take a look at how we can compose the views by using the mixin classes. Here's our <code>views.py</code> module again.</p>
|
||||
<pre><code>from snippets.models import Snippet
|
||||
<pre><code class="language-python">from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
from rest_framework import mixins
|
||||
from rest_framework import generics
|
||||
|
||||
class SnippetList(mixins.ListModelMixin,
|
||||
mixins.CreateModelMixin,
|
||||
generics.GenericAPIView):
|
||||
|
||||
class SnippetList(
|
||||
mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView
|
||||
):
|
||||
queryset = Snippet.objects.all()
|
||||
serializer_class = SnippetSerializer
|
||||
|
||||
|
@ -542,10 +545,12 @@ class SnippetList(mixins.ListModelMixin,
|
|||
</code></pre>
|
||||
<p>We'll take a moment to examine exactly what's happening here. We're building our view using <code>GenericAPIView</code>, and adding in <code>ListModelMixin</code> and <code>CreateModelMixin</code>.</p>
|
||||
<p>The base class provides the core functionality, and the mixin classes provide the <code>.list()</code> and <code>.create()</code> actions. We're then explicitly binding the <code>get</code> and <code>post</code> methods to the appropriate actions. Simple enough stuff so far.</p>
|
||||
<pre><code>class SnippetDetail(mixins.RetrieveModelMixin,
|
||||
mixins.UpdateModelMixin,
|
||||
mixins.DestroyModelMixin,
|
||||
generics.GenericAPIView):
|
||||
<pre><code class="language-python">class SnippetDetail(
|
||||
mixins.RetrieveModelMixin,
|
||||
mixins.UpdateModelMixin,
|
||||
mixins.DestroyModelMixin,
|
||||
generics.GenericAPIView,
|
||||
):
|
||||
queryset = Snippet.objects.all()
|
||||
serializer_class = SnippetSerializer
|
||||
|
||||
|
@ -561,7 +566,7 @@ class SnippetList(mixins.ListModelMixin,
|
|||
<p>Pretty similar. Again we're using the <code>GenericAPIView</code> class to provide the core functionality, and adding in mixins to provide the <code>.retrieve()</code>, <code>.update()</code> and <code>.destroy()</code> actions.</p>
|
||||
<h2 id="using-generic-class-based-views"><a class="toclink" href="#using-generic-class-based-views">Using generic class-based views</a></h2>
|
||||
<p>Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our <code>views.py</code> module even more.</p>
|
||||
<pre><code>from snippets.models import Snippet
|
||||
<pre><code class="language-python">from snippets.models import Snippet
|
||||
from snippets.serializers import SnippetSerializer
|
||||
from rest_framework import generics
|
||||
|
||||
|
|
|
@ -484,53 +484,57 @@
|
|||
<p>We're going to make a couple of changes to our <code>Snippet</code> model class.
|
||||
First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.</p>
|
||||
<p>Add the following two fields to the <code>Snippet</code> model in <code>models.py</code>.</p>
|
||||
<pre><code>owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
|
||||
<pre><code class="language-python">owner = models.ForeignKey(
|
||||
"auth.User", related_name="snippets", on_delete=models.CASCADE
|
||||
)
|
||||
highlighted = models.TextField()
|
||||
</code></pre>
|
||||
<p>We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the <code>pygments</code> code highlighting library.</p>
|
||||
<p>We'll need some extra imports:</p>
|
||||
<pre><code>from pygments.lexers import get_lexer_by_name
|
||||
<pre><code class="language-python">from pygments.lexers import get_lexer_by_name
|
||||
from pygments.formatters.html import HtmlFormatter
|
||||
from pygments import highlight
|
||||
</code></pre>
|
||||
<p>And now we can add a <code>.save()</code> method to our model class:</p>
|
||||
<pre><code>def save(self, *args, **kwargs):
|
||||
"""
|
||||
<pre><code class="language-python">def save(self, *args, **kwargs):
|
||||
"""
|
||||
Use the `pygments` library to create a highlighted HTML
|
||||
representation of the code snippet.
|
||||
"""
|
||||
"""
|
||||
lexer = get_lexer_by_name(self.language)
|
||||
linenos = 'table' if self.linenos else False
|
||||
options = {'title': self.title} if self.title else {}
|
||||
formatter = HtmlFormatter(style=self.style, linenos=linenos,
|
||||
full=True, **options)
|
||||
linenos = "table" if self.linenos else False
|
||||
options = {"title": self.title} if self.title else {}
|
||||
formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
|
||||
self.highlighted = highlight(self.code, lexer, formatter)
|
||||
super().save(*args, **kwargs)
|
||||
</code></pre>
|
||||
<p>When that's all done we'll need to update our database tables.
|
||||
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.</p>
|
||||
<pre><code>rm -f db.sqlite3
|
||||
<pre><code class="language-bash">rm -f db.sqlite3
|
||||
rm -r snippets/migrations
|
||||
python manage.py makemigrations snippets
|
||||
python manage.py migrate
|
||||
</code></pre>
|
||||
<p>You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the <code>createsuperuser</code> command.</p>
|
||||
<pre><code>python manage.py createsuperuser
|
||||
<pre><code class="language-bash">python manage.py createsuperuser
|
||||
</code></pre>
|
||||
<h2 id="adding-endpoints-for-our-user-models"><a class="toclink" href="#adding-endpoints-for-our-user-models">Adding endpoints for our User models</a></h2>
|
||||
<p>Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In <code>serializers.py</code> add:</p>
|
||||
<pre><code>from django.contrib.auth.models import User
|
||||
<pre><code class="language-python">from django.contrib.auth.models import User
|
||||
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
|
||||
snippets = serializers.PrimaryKeyRelatedField(
|
||||
many=True, queryset=Snippet.objects.all()
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ['id', 'username', 'snippets']
|
||||
fields = ["id", "username", "snippets"]
|
||||
</code></pre>
|
||||
<p>Because <code>'snippets'</code> is a <em>reverse</em> relationship on the User model, it will not be included by default when using the <code>ModelSerializer</code> class, so we needed to add an explicit field for it.</p>
|
||||
<p>We'll also add a couple of views to <code>views.py</code>. We'd like to just use read-only views for the user representations, so we'll use the <code>ListAPIView</code> and <code>RetrieveAPIView</code> generic class-based views.</p>
|
||||
<pre><code>from django.contrib.auth.models import User
|
||||
<pre><code class="language-python">from django.contrib.auth.models import User
|
||||
|
||||
|
||||
class UserList(generics.ListAPIView):
|
||||
|
@ -543,23 +547,23 @@ class UserDetail(generics.RetrieveAPIView):
|
|||
serializer_class = UserSerializer
|
||||
</code></pre>
|
||||
<p>Make sure to also import the <code>UserSerializer</code> class</p>
|
||||
<pre><code>from snippets.serializers import UserSerializer
|
||||
<pre><code class="language-python">from snippets.serializers import UserSerializer
|
||||
</code></pre>
|
||||
<p>Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in <code>snippets/urls.py</code>.</p>
|
||||
<pre><code>path('users/', views.UserList.as_view()),
|
||||
path('users/<int:pk>/', views.UserDetail.as_view()),
|
||||
<pre><code class="language-python">path("users/", views.UserList.as_view()),
|
||||
path("users/<int:pk>/", views.UserDetail.as_view()),
|
||||
</code></pre>
|
||||
<h2 id="associating-snippets-with-users"><a class="toclink" href="#associating-snippets-with-users">Associating Snippets with Users</a></h2>
|
||||
<p>Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.</p>
|
||||
<p>The way we deal with that is by overriding a <code>.perform_create()</code> method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.</p>
|
||||
<p>On the <code>SnippetList</code> view class, add the following method:</p>
|
||||
<pre><code>def perform_create(self, serializer):
|
||||
<pre><code class="language-python">def perform_create(self, serializer):
|
||||
serializer.save(owner=self.request.user)
|
||||
</code></pre>
|
||||
<p>The <code>create()</code> method of our serializer will now be passed an additional <code>'owner'</code> field, along with the validated data from the request.</p>
|
||||
<h2 id="updating-our-serializer"><a class="toclink" href="#updating-our-serializer">Updating our serializer</a></h2>
|
||||
<p>Now that snippets are associated with the user that created them, let's update our <code>SnippetSerializer</code> to reflect that. Add the following field to the serializer definition in <code>serializers.py</code>:</p>
|
||||
<pre><code>owner = serializers.ReadOnlyField(source='owner.username')
|
||||
<pre><code class="language-python">owner = serializers.ReadOnlyField(source="owner.username")
|
||||
</code></pre>
|
||||
<p><strong>Note</strong>: Make sure you also add <code>'owner',</code> to the list of fields in the inner <code>Meta</code> class.</p>
|
||||
<p>This field is doing something quite interesting. The <code>source</code> argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.</p>
|
||||
|
@ -568,20 +572,20 @@ path('users/<int:pk>/', views.UserDetail.as_view()),
|
|||
<p>Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.</p>
|
||||
<p>REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is <code>IsAuthenticatedOrReadOnly</code>, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.</p>
|
||||
<p>First add the following import in the views module</p>
|
||||
<pre><code>from rest_framework import permissions
|
||||
<pre><code class="language-python">from rest_framework import permissions
|
||||
</code></pre>
|
||||
<p>Then, add the following property to <strong>both</strong> the <code>SnippetList</code> and <code>SnippetDetail</code> view classes.</p>
|
||||
<pre><code>permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||
<pre><code class="language-python">permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||
</code></pre>
|
||||
<h2 id="adding-login-to-the-browsable-api"><a class="toclink" href="#adding-login-to-the-browsable-api">Adding login to the Browsable API</a></h2>
|
||||
<p>If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.</p>
|
||||
<p>We can add a login view for use with the browsable API, by editing the URLconf in our project-level <code>urls.py</code> file.</p>
|
||||
<p>Add the following import at the top of the file:</p>
|
||||
<pre><code>from django.urls import path, include
|
||||
<pre><code class="language-python">from django.urls import path, include
|
||||
</code></pre>
|
||||
<p>And, at the end of the file, add a pattern to include the login and logout views for the browsable API.</p>
|
||||
<pre><code>urlpatterns += [
|
||||
path('api-auth/', include('rest_framework.urls')),
|
||||
<pre><code class="language-python">urlpatterns += [
|
||||
path("api-auth/", include("rest_framework.urls")),
|
||||
]
|
||||
</code></pre>
|
||||
<p>The <code>'api-auth/'</code> part of pattern can actually be whatever URL you want to use.</p>
|
||||
|
@ -591,13 +595,13 @@ path('users/<int:pk>/', views.UserDetail.as_view()),
|
|||
<p>Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.</p>
|
||||
<p>To do that we're going to need to create a custom permission.</p>
|
||||
<p>In the snippets app, create a new file, <code>permissions.py</code></p>
|
||||
<pre><code>from rest_framework import permissions
|
||||
<pre><code class="language-python">from rest_framework import permissions
|
||||
|
||||
|
||||
class IsOwnerOrReadOnly(permissions.BasePermission):
|
||||
"""
|
||||
"""
|
||||
Custom permission to only allow owners of an object to edit it.
|
||||
"""
|
||||
"""
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
# Read permissions are allowed to any request,
|
||||
|
@ -609,11 +613,10 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
|
|||
return obj.owner == request.user
|
||||
</code></pre>
|
||||
<p>Now we can add that custom permission to our snippet instance endpoint, by editing the <code>permission_classes</code> property on the <code>SnippetDetail</code> view class:</p>
|
||||
<pre><code>permission_classes = [permissions.IsAuthenticatedOrReadOnly,
|
||||
IsOwnerOrReadOnly]
|
||||
<pre><code class="language-python">permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
|
||||
</code></pre>
|
||||
<p>Make sure to also import the <code>IsOwnerOrReadOnly</code> class.</p>
|
||||
<pre><code>from snippets.permissions import IsOwnerOrReadOnly
|
||||
<pre><code class="language-python">from snippets.permissions import IsOwnerOrReadOnly
|
||||
</code></pre>
|
||||
<p>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.</p>
|
||||
<h2 id="authenticating-with-the-api"><a class="toclink" href="#authenticating-with-the-api">Authenticating with the API</a></h2>
|
||||
|
@ -621,23 +624,23 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
|
|||
<p>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.</p>
|
||||
<p>If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.</p>
|
||||
<p>If we try to create a snippet without authenticating, we'll get an error:</p>
|
||||
<pre><code>http POST http://127.0.0.1:8000/snippets/ code="print(123)"
|
||||
<pre><code class="language-bash">http POST http://127.0.0.1:8000/snippets/ code="print(123)"
|
||||
|
||||
{
|
||||
"detail": "Authentication credentials were not provided."
|
||||
"detail": "Authentication credentials were not provided."
|
||||
}
|
||||
</code></pre>
|
||||
<p>We can make a successful request by including the username and password of one of the users we created earlier.</p>
|
||||
<pre><code>http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
|
||||
<pre><code class="language-bash">http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)"
|
||||
|
||||
{
|
||||
"id": 1,
|
||||
"owner": "admin",
|
||||
"title": "foo",
|
||||
"code": "print(789)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
"id": 1,
|
||||
"owner": "admin",
|
||||
"title": "foo",
|
||||
"code": "print(789)",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
</code></pre>
|
||||
<h2 id="summary"><a class="toclink" href="#summary">Summary</a></h2>
|
||||
|
|
|
@ -464,17 +464,19 @@
|
|||
<p>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.</p>
|
||||
<h2 id="creating-an-endpoint-for-the-root-of-our-api"><a class="toclink" href="#creating-an-endpoint-for-the-root-of-our-api">Creating an endpoint for the root of our API</a></h2>
|
||||
<p>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 <code>@api_view</code> decorator we introduced earlier. In your <code>snippets/views.py</code> add:</p>
|
||||
<pre><code>from rest_framework.decorators import api_view
|
||||
<pre><code class="language-python">from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.reverse import reverse
|
||||
|
||||
|
||||
@api_view(['GET'])
|
||||
@api_view(["GET"])
|
||||
def api_root(request, format=None):
|
||||
return Response({
|
||||
'users': reverse('user-list', request=request, format=format),
|
||||
'snippets': reverse('snippet-list', request=request, format=format)
|
||||
})
|
||||
return Response(
|
||||
{
|
||||
"users": reverse("user-list", request=request, format=format),
|
||||
"snippets": reverse("snippet-list", request=request, format=format),
|
||||
}
|
||||
)
|
||||
</code></pre>
|
||||
<p>Two things should be noticed here. First, we're using REST framework's <code>reverse</code> function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our <code>snippets/urls.py</code>.</p>
|
||||
<h2 id="creating-an-endpoint-for-the-highlighted-snippets"><a class="toclink" href="#creating-an-endpoint-for-the-highlighted-snippets">Creating an endpoint for the highlighted snippets</a></h2>
|
||||
|
@ -482,7 +484,8 @@ def api_root(request, format=None):
|
|||
<p>Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.</p>
|
||||
<p>The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.</p>
|
||||
<p>Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own <code>.get()</code> method. In your <code>snippets/views.py</code> add:</p>
|
||||
<pre><code>from rest_framework import renderers
|
||||
<pre><code class="language-python">from rest_framework import renderers
|
||||
|
||||
|
||||
class SnippetHighlight(generics.GenericAPIView):
|
||||
queryset = Snippet.objects.all()
|
||||
|
@ -494,10 +497,10 @@ class SnippetHighlight(generics.GenericAPIView):
|
|||
</code></pre>
|
||||
<p>As usual we need to add the new views that we've created in to our URLconf.
|
||||
We'll add a url pattern for our new API root in <code>snippets/urls.py</code>:</p>
|
||||
<pre><code>path('', views.api_root),
|
||||
<pre><code class="language-python">path("", views.api_root),
|
||||
</code></pre>
|
||||
<p>And then add a url pattern for the snippet highlights:</p>
|
||||
<pre><code>path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view()),
|
||||
<pre><code class="language-python">path("snippets/<int:pk>/highlight/", views.SnippetHighlight.as_view()),
|
||||
</code></pre>
|
||||
<h2 id="hyperlinking-our-api"><a class="toclink" href="#hyperlinking-our-api">Hyperlinking our API</a></h2>
|
||||
<p>Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:</p>
|
||||
|
@ -519,32 +522,45 @@ We'll add a url pattern for our new API root in <code>snippets/urls.py</code>:</
|
|||
instead of <code>PrimaryKeyRelatedField</code>.</li>
|
||||
</ul>
|
||||
<p>We can easily re-write our existing serializers to use hyperlinking. In your <code>snippets/serializers.py</code> add:</p>
|
||||
<pre><code>class SnippetSerializer(serializers.HyperlinkedModelSerializer):
|
||||
owner = serializers.ReadOnlyField(source='owner.username')
|
||||
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
|
||||
<pre><code class="language-python">class SnippetSerializer(serializers.HyperlinkedModelSerializer):
|
||||
owner = serializers.ReadOnlyField(source="owner.username")
|
||||
highlight = serializers.HyperlinkedIdentityField(
|
||||
view_name="snippet-highlight", format="html"
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Snippet
|
||||
fields = ['url', 'id', 'highlight', 'owner',
|
||||
'title', 'code', 'linenos', 'language', 'style']
|
||||
fields = [
|
||||
"url",
|
||||
"id",
|
||||
"highlight",
|
||||
"owner",
|
||||
"title",
|
||||
"code",
|
||||
"linenos",
|
||||
"language",
|
||||
"style",
|
||||
]
|
||||
|
||||
|
||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)
|
||||
snippets = serializers.HyperlinkedRelatedField(
|
||||
many=True, view_name="snippet-detail", read_only=True
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ['url', 'id', 'username', 'snippets']
|
||||
fields = ["url", "id", "username", "snippets"]
|
||||
</code></pre>
|
||||
<p>Notice that we've also added a new <code>'highlight'</code> field. This field is of the same type as the <code>url</code> field, except that it points to the <code>'snippet-highlight'</code> url pattern, instead of the <code>'snippet-detail'</code> url pattern.</p>
|
||||
<p>Because we've included format suffixed URLs such as <code>'.json'</code>, we also need to indicate on the <code>highlight</code> field that any format suffixed hyperlinks it returns should use the <code>'.html'</code> suffix.</p>
|
||||
<hr />
|
||||
<p><strong>Note:</strong></p>
|
||||
<p>When you are manually instantiating these serializers inside your views (e.g., in <code>SnippetDetail</code> or <code>SnippetList</code>), you <strong>must</strong> pass <code>context={'request': request}</code> so the serializer knows how to build absolute URLs. For example, instead of:</p>
|
||||
<pre><code>serializer = SnippetSerializer(snippet)
|
||||
<pre><code class="language-python">serializer = SnippetSerializer(snippet)
|
||||
</code></pre>
|
||||
<p>You must write:</p>
|
||||
<pre><code>serializer = SnippetSerializer(snippet, context={'request': request})
|
||||
<pre><code class="language-python">serializer = SnippetSerializer(snippet, context={"request": request})
|
||||
</code></pre>
|
||||
<p>If your view is a subclass of <code>GenericAPIView</code>, you may use the <code>get_serializer_context()</code> as a convenience method.</p>
|
||||
<hr />
|
||||
|
@ -557,36 +573,34 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
|
|||
<li>Our snippet and user serializers include <code>'url'</code> fields that by default will refer to <code>'{model_name}-detail'</code>, which in this case will be <code>'snippet-detail'</code> and <code>'user-detail'</code>.</li>
|
||||
</ul>
|
||||
<p>After adding all those names into our URLconf, our final <code>snippets/urls.py</code> file should look like this:</p>
|
||||
<pre><code>from django.urls import path
|
||||
<pre><code class="language-python">from django.urls import path
|
||||
from rest_framework.urlpatterns import format_suffix_patterns
|
||||
from snippets import views
|
||||
|
||||
# API endpoints
|
||||
urlpatterns = format_suffix_patterns([
|
||||
path('', views.api_root),
|
||||
path('snippets/',
|
||||
views.SnippetList.as_view(),
|
||||
name='snippet-list'),
|
||||
path('snippets/<int:pk>/',
|
||||
views.SnippetDetail.as_view(),
|
||||
name='snippet-detail'),
|
||||
path('snippets/<int:pk>/highlight/',
|
||||
views.SnippetHighlight.as_view(),
|
||||
name='snippet-highlight'),
|
||||
path('users/',
|
||||
views.UserList.as_view(),
|
||||
name='user-list'),
|
||||
path('users/<int:pk>/',
|
||||
views.UserDetail.as_view(),
|
||||
name='user-detail')
|
||||
])
|
||||
urlpatterns = format_suffix_patterns(
|
||||
[
|
||||
path("", views.api_root),
|
||||
path("snippets/", views.SnippetList.as_view(), name="snippet-list"),
|
||||
path(
|
||||
"snippets/<int:pk>/", views.SnippetDetail.as_view(), name="snippet-detail"
|
||||
),
|
||||
path(
|
||||
"snippets/<int:pk>/highlight/",
|
||||
views.SnippetHighlight.as_view(),
|
||||
name="snippet-highlight",
|
||||
),
|
||||
path("users/", views.UserList.as_view(), name="user-list"),
|
||||
path("users/<int:pk>/", views.UserDetail.as_view(), name="user-detail"),
|
||||
]
|
||||
)
|
||||
</code></pre>
|
||||
<h2 id="adding-pagination"><a class="toclink" href="#adding-pagination">Adding pagination</a></h2>
|
||||
<p>The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.</p>
|
||||
<p>We can change the default list style to use pagination, by modifying our <code>tutorial/settings.py</code> file slightly. Add the following setting:</p>
|
||||
<pre><code>REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
|
||||
'PAGE_SIZE': 10
|
||||
<pre><code class="language-python">REST_FRAMEWORK = {
|
||||
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
|
||||
"PAGE_SIZE": 10,
|
||||
}
|
||||
</code></pre>
|
||||
<p>Note that settings in REST framework are all namespaced into a single dictionary setting, named <code>REST_FRAMEWORK</code>, which helps keep them well separated from your other project settings.</p>
|
||||
|
|
|
@ -459,35 +459,36 @@
|
|||
<h2 id="refactoring-to-use-viewsets"><a class="toclink" href="#refactoring-to-use-viewsets">Refactoring to use ViewSets</a></h2>
|
||||
<p>Let's take our current set of views, and refactor them into view sets.</p>
|
||||
<p>First of all let's refactor our <code>UserList</code> and <code>UserDetail</code> classes into a single <code>UserViewSet</code> class. In the <code>snippets/views.py</code> file, we can remove the two view classes and replace them with a single ViewSet class:</p>
|
||||
<pre><code>from rest_framework import viewsets
|
||||
<pre><code class="language-python">from rest_framework import viewsets
|
||||
|
||||
|
||||
class UserViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
"""
|
||||
"""
|
||||
This viewset automatically provides `list` and `retrieve` actions.
|
||||
"""
|
||||
"""
|
||||
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
</code></pre>
|
||||
<p>Here we've used the <code>ReadOnlyModelViewSet</code> class to automatically provide the default 'read-only' operations. We're still setting the <code>queryset</code> and <code>serializer_class</code> attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.</p>
|
||||
<p>Next we're going to replace the <code>SnippetList</code>, <code>SnippetDetail</code> and <code>SnippetHighlight</code> view classes. We can remove the three views, and again replace them with a single class.</p>
|
||||
<pre><code>from rest_framework import permissions
|
||||
<pre><code class="language-python">from rest_framework import permissions
|
||||
from rest_framework import renderers
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
|
||||
|
||||
class SnippetViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
"""
|
||||
This ViewSet automatically provides `list`, `create`, `retrieve`,
|
||||
`update` and `destroy` actions.
|
||||
|
||||
Additionally we also provide an extra `highlight` action.
|
||||
"""
|
||||
"""
|
||||
|
||||
queryset = Snippet.objects.all()
|
||||
serializer_class = SnippetSerializer
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly,
|
||||
IsOwnerOrReadOnly]
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
|
||||
|
||||
@action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
|
||||
def highlight(self, request, *args, **kwargs):
|
||||
|
@ -505,57 +506,51 @@ class SnippetViewSet(viewsets.ModelViewSet):
|
|||
<p>The handler methods only get bound to the actions when we define the URLConf.
|
||||
To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.</p>
|
||||
<p>In the <code>snippets/urls.py</code> file we bind our <code>ViewSet</code> classes into a set of concrete views.</p>
|
||||
<pre><code>from rest_framework import renderers
|
||||
<pre><code class="language-python">from rest_framework import renderers
|
||||
|
||||
from snippets.views import api_root, SnippetViewSet, UserViewSet
|
||||
|
||||
snippet_list = SnippetViewSet.as_view({
|
||||
'get': 'list',
|
||||
'post': 'create'
|
||||
})
|
||||
snippet_detail = SnippetViewSet.as_view({
|
||||
'get': 'retrieve',
|
||||
'put': 'update',
|
||||
'patch': 'partial_update',
|
||||
'delete': 'destroy'
|
||||
})
|
||||
snippet_highlight = SnippetViewSet.as_view({
|
||||
'get': 'highlight'
|
||||
}, renderer_classes=[renderers.StaticHTMLRenderer])
|
||||
user_list = UserViewSet.as_view({
|
||||
'get': 'list'
|
||||
})
|
||||
user_detail = UserViewSet.as_view({
|
||||
'get': 'retrieve'
|
||||
})
|
||||
snippet_list = SnippetViewSet.as_view({"get": "list", "post": "create"})
|
||||
snippet_detail = SnippetViewSet.as_view(
|
||||
{"get": "retrieve", "put": "update", "patch": "partial_update", "delete": "destroy"}
|
||||
)
|
||||
snippet_highlight = SnippetViewSet.as_view(
|
||||
{"get": "highlight"}, renderer_classes=[renderers.StaticHTMLRenderer]
|
||||
)
|
||||
user_list = UserViewSet.as_view({"get": "list"})
|
||||
user_detail = UserViewSet.as_view({"get": "retrieve"})
|
||||
</code></pre>
|
||||
<p>Notice how we're creating multiple views from each <code>ViewSet</code> class, by binding the HTTP methods to the required action for each view.</p>
|
||||
<p>Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.</p>
|
||||
<pre><code>urlpatterns = format_suffix_patterns([
|
||||
path('', api_root),
|
||||
path('snippets/', snippet_list, name='snippet-list'),
|
||||
path('snippets/<int:pk>/', snippet_detail, name='snippet-detail'),
|
||||
path('snippets/<int:pk>/highlight/', snippet_highlight, name='snippet-highlight'),
|
||||
path('users/', user_list, name='user-list'),
|
||||
path('users/<int:pk>/', user_detail, name='user-detail')
|
||||
])
|
||||
<pre><code class="language-python">urlpatterns = format_suffix_patterns(
|
||||
[
|
||||
path("", api_root),
|
||||
path("snippets/", snippet_list, name="snippet-list"),
|
||||
path("snippets/<int:pk>/", snippet_detail, name="snippet-detail"),
|
||||
path(
|
||||
"snippets/<int:pk>/highlight/", snippet_highlight, name="snippet-highlight"
|
||||
),
|
||||
path("users/", user_list, name="user-list"),
|
||||
path("users/<int:pk>/", user_detail, name="user-detail"),
|
||||
]
|
||||
)
|
||||
</code></pre>
|
||||
<h2 id="using-routers"><a class="toclink" href="#using-routers">Using Routers</a></h2>
|
||||
<p>Because we're using <code>ViewSet</code> classes rather than <code>View</code> classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a <code>Router</code> class. All we need to do is register the appropriate view sets with a router, and let it do the rest.</p>
|
||||
<p>Here's our re-wired <code>snippets/urls.py</code> file.</p>
|
||||
<pre><code>from django.urls import path, include
|
||||
<pre><code class="language-python">from django.urls import path, include
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from snippets import views
|
||||
|
||||
# Create a router and register our ViewSets with it.
|
||||
router = DefaultRouter()
|
||||
router.register(r'snippets', views.SnippetViewSet, basename='snippet')
|
||||
router.register(r'users', views.UserViewSet, basename='user')
|
||||
router.register(r"snippets", views.SnippetViewSet, basename="snippet")
|
||||
router.register(r"users", views.UserViewSet, basename="user")
|
||||
|
||||
# The API URLs are now determined automatically by the router.
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path("", include(router.urls)),
|
||||
]
|
||||
</code></pre>
|
||||
<p>Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself.</p>
|
||||
|
|
|
@ -468,7 +468,7 @@
|
|||
<p>We're going to create a simple API to allow admin users to view and edit the users and groups in the system.</p>
|
||||
<h2 id="project-setup"><a class="toclink" href="#project-setup">Project setup</a></h2>
|
||||
<p>Create a new Django project named <code>tutorial</code>, then start a new app called <code>quickstart</code>.</p>
|
||||
<pre><code># Create the project directory
|
||||
<pre><code class="language-bash"># Create the project directory
|
||||
mkdir tutorial
|
||||
cd tutorial
|
||||
|
||||
|
@ -486,7 +486,7 @@ django-admin startapp quickstart
|
|||
cd ..
|
||||
</code></pre>
|
||||
<p>The project layout should look like:</p>
|
||||
<pre><code>$ pwd
|
||||
<pre><code class="language-bash">$ pwd
|
||||
<some path>/tutorial
|
||||
$ find .
|
||||
.
|
||||
|
@ -511,52 +511,54 @@ $ find .
|
|||
</code></pre>
|
||||
<p>It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).</p>
|
||||
<p>Now sync your database for the first time:</p>
|
||||
<pre><code>python manage.py migrate
|
||||
<pre><code class="language-bash">python manage.py migrate
|
||||
</code></pre>
|
||||
<p>We'll also create an initial user named <code>admin</code> with a password. We'll authenticate as that user later in our example.</p>
|
||||
<pre><code>python manage.py createsuperuser --username admin --email admin@example.com
|
||||
<pre><code class="language-bash">python manage.py createsuperuser --username admin --email admin@example.com
|
||||
</code></pre>
|
||||
<p>Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...</p>
|
||||
<h2 id="serializers"><a class="toclink" href="#serializers">Serializers</a></h2>
|
||||
<p>First up we're going to define some serializers. Let's create a new module named <code>tutorial/quickstart/serializers.py</code> that we'll use for our data representations.</p>
|
||||
<pre><code>from django.contrib.auth.models import Group, User
|
||||
<pre><code class="language-python">from django.contrib.auth.models import Group, User
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ['url', 'username', 'email', 'groups']
|
||||
fields = ["url", "username", "email", "groups"]
|
||||
|
||||
|
||||
class GroupSerializer(serializers.HyperlinkedModelSerializer):
|
||||
class Meta:
|
||||
model = Group
|
||||
fields = ['url', 'name']
|
||||
fields = ["url", "name"]
|
||||
</code></pre>
|
||||
<p>Notice that we're using hyperlinked relations in this case with <code>HyperlinkedModelSerializer</code>. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.</p>
|
||||
<h2 id="views"><a class="toclink" href="#views">Views</a></h2>
|
||||
<p>Right, we'd better write some views then. Open <code>tutorial/quickstart/views.py</code> and get typing.</p>
|
||||
<pre><code>from django.contrib.auth.models import Group, User
|
||||
<pre><code class="language-python">from django.contrib.auth.models import Group, User
|
||||
from rest_framework import permissions, viewsets
|
||||
|
||||
from tutorial.quickstart.serializers import GroupSerializer, UserSerializer
|
||||
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
"""
|
||||
API endpoint that allows users to be viewed or edited.
|
||||
"""
|
||||
queryset = User.objects.all().order_by('-date_joined')
|
||||
"""
|
||||
|
||||
queryset = User.objects.all().order_by("-date_joined")
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
|
||||
|
||||
class GroupViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
"""
|
||||
API endpoint that allows groups to be viewed or edited.
|
||||
"""
|
||||
queryset = Group.objects.all().order_by('name')
|
||||
"""
|
||||
|
||||
queryset = Group.objects.all().order_by("name")
|
||||
serializer_class = GroupSerializer
|
||||
permission_classes = [permissions.IsAuthenticated]
|
||||
</code></pre>
|
||||
|
@ -564,20 +566,20 @@ class GroupViewSet(viewsets.ModelViewSet):
|
|||
<p>We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.</p>
|
||||
<h2 id="urls"><a class="toclink" href="#urls">URLs</a></h2>
|
||||
<p>Okay, now let's wire up the API URLs. On to <code>tutorial/urls.py</code>...</p>
|
||||
<pre><code>from django.urls import include, path
|
||||
<pre><code class="language-python">from django.urls import include, path
|
||||
from rest_framework import routers
|
||||
|
||||
from tutorial.quickstart import views
|
||||
|
||||
router = routers.DefaultRouter()
|
||||
router.register(r'users', views.UserViewSet)
|
||||
router.register(r'groups', views.GroupViewSet)
|
||||
router.register(r"users", views.UserViewSet)
|
||||
router.register(r"groups", views.GroupViewSet)
|
||||
|
||||
# Wire up our API using automatic URL routing.
|
||||
# Additionally, we include login URLs for the browsable API.
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||
path("", include(router.urls)),
|
||||
path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
|
||||
]
|
||||
</code></pre>
|
||||
<p>Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.</p>
|
||||
|
@ -585,14 +587,14 @@ urlpatterns = [
|
|||
<p>Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.</p>
|
||||
<h2 id="pagination"><a class="toclink" href="#pagination">Pagination</a></h2>
|
||||
<p>Pagination allows you to control how many objects per page are returned. To enable it add the following lines to <code>tutorial/settings.py</code></p>
|
||||
<pre><code>REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
|
||||
'PAGE_SIZE': 10
|
||||
<pre><code class="language-python">REST_FRAMEWORK = {
|
||||
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
|
||||
"PAGE_SIZE": 10,
|
||||
}
|
||||
</code></pre>
|
||||
<h2 id="settings"><a class="toclink" href="#settings">Settings</a></h2>
|
||||
<p>Add <code>'rest_framework'</code> to <code>INSTALLED_APPS</code>. The settings module will be in <code>tutorial/settings.py</code></p>
|
||||
<pre><code>INSTALLED_APPS = [
|
||||
<pre><code class="language-text">INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
|
@ -601,40 +603,40 @@ urlpatterns = [
|
|||
<hr />
|
||||
<h2 id="testing-our-api"><a class="toclink" href="#testing-our-api">Testing our API</a></h2>
|
||||
<p>We're now ready to test the API we've built. Let's fire up the server from the command line.</p>
|
||||
<pre><code>python manage.py runserver
|
||||
<pre><code class="language-bash">python manage.py runserver
|
||||
</code></pre>
|
||||
<p>We can now access our API, both from the command-line, using tools like <code>curl</code>...</p>
|
||||
<pre><code>bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
|
||||
<pre><code class="language-bash">bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
|
||||
Enter host password for user 'admin':
|
||||
{
|
||||
"count": 1,
|
||||
"next": null,
|
||||
"previous": null,
|
||||
"results": [
|
||||
"count": 1,
|
||||
"next": null,
|
||||
"previous": null,
|
||||
"results": [
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/users/1/",
|
||||
"username": "admin",
|
||||
"email": "admin@example.com",
|
||||
"groups": []
|
||||
"url": "http://127.0.0.1:8000/users/1/",
|
||||
"username": "admin",
|
||||
"email": "admin@example.com",
|
||||
"groups": []
|
||||
}
|
||||
]
|
||||
}
|
||||
</code></pre>
|
||||
<p>Or using the <a href="https://httpie.io/docs#installation">httpie</a>, command line tool...</p>
|
||||
<pre><code>bash: http -a admin http://127.0.0.1:8000/users/
|
||||
<pre><code class="language-bash">bash: http -a admin http://127.0.0.1:8000/users/
|
||||
http: password for admin@127.0.0.1:8000::
|
||||
$HTTP/1.1 200 OK
|
||||
...
|
||||
{
|
||||
"count": 1,
|
||||
"next": null,
|
||||
"previous": null,
|
||||
"results": [
|
||||
"count": 1,
|
||||
"next": null,
|
||||
"previous": null,
|
||||
"results": [
|
||||
{
|
||||
"email": "admin@example.com",
|
||||
"groups": [],
|
||||
"url": "http://127.0.0.1:8000/users/1/",
|
||||
"username": "admin"
|
||||
"email": "admin@example.com",
|
||||
"groups": [],
|
||||
"url": "http://127.0.0.1:8000/users/1/",
|
||||
"username": "admin"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user