Compare commits
449 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
ea1da76196 | ||
|
2fbfaae507 | ||
|
3c755794df | ||
|
c41314f1fc | ||
|
5c21fa757c | ||
|
141ab8e585 | ||
|
3ba8ef967e | ||
|
9b1e8d2d43 | ||
|
ffadde930e | ||
|
6f274ab862 | ||
|
ac50cec76c | ||
|
e96b8e49cd | ||
|
32dbd3525d | ||
|
73cbb9cd4a | ||
|
1e8ac7c23b | ||
|
0e1c7d3613 | ||
|
fc98d3598d | ||
|
17e95604f5 | ||
|
f30c0e2eed | ||
|
28d0261afc | ||
|
8637b3d624 | ||
|
038670a4cf | ||
|
f8dbea1a45 | ||
|
e1c070aacc | ||
|
78e0b84ac9 | ||
|
b483179b93 | ||
|
4a1d773b8f | ||
|
a4f6059d50 | ||
|
089f6a6974 | ||
|
a8595a8eae | ||
|
dbac145638 | ||
|
b31413d46d | ||
|
9016efe3fc | ||
|
d3dd45b3f4 | ||
|
10b25e7d63 | ||
|
81613c0e51 | ||
|
9921c7554f | ||
|
b25028ac8f | ||
|
a59aa2dfe1 | ||
|
61e33761eb | ||
|
7141bdb2df | ||
|
2ede857de0 | ||
|
125ad42eb3 | ||
|
f593f5752c | ||
|
5cc1028c2f | ||
|
f6ea019bd9 | ||
|
2f28e7086d | ||
|
f113ab6b68 | ||
|
518eb22e67 | ||
|
8e304e1adb | ||
|
b6ea11028f | ||
|
f74185b6dd | ||
|
ccfe0a9637 | ||
|
e9f3fd250a | ||
|
4d0662663a | ||
|
7297f19701 | ||
|
e13688f0c0 | ||
|
1e9b5c15ec | ||
|
c7a7eae551 | ||
|
3b41f01241 | ||
|
fe92f0dd0d | ||
|
fbdab09c77 | ||
|
36d5c0e74f | ||
|
9d4ed054bf | ||
|
b34bde47d7 | ||
|
ab681f2d5e | ||
|
22377241a8 | ||
|
d58b8da591 | ||
|
d38aab39e4 | ||
|
82d91a85ff | ||
|
1f2daaf53c | ||
|
91bbac1f67 | ||
|
7900778fbe | ||
|
861b7ac42b | ||
|
52bfe20dec | ||
|
f642d85be2 | ||
|
430de731e7 | ||
|
e596f43c4e | ||
|
7f18ec1b53 | ||
|
f96c065607 | ||
|
97c5617edc | ||
|
f4daa98f48 | ||
|
9864c47018 | ||
|
63063da082 | ||
|
085b7e166b | ||
|
f4194c4684 | ||
|
6df509863d | ||
|
328591693d | ||
|
eb361d289d | ||
|
400b4c5441 | ||
|
4ef3aaf0ad | ||
|
4f10c4e43e | ||
|
a4d58077a0 | ||
|
da78a147f2 | ||
|
0e4ed81627 | ||
|
56a5b354d0 | ||
|
d7c8dcfc7e | ||
|
77ef27f18f | ||
|
2f66c294e3 | ||
|
337ba211e8 | ||
|
2d8e9ad819 | ||
|
a677b09729 | ||
|
09a0c551ca | ||
|
730d216794 | ||
|
a2eabfc867 | ||
|
4c7c693f15 | ||
|
b7cccff943 | ||
|
6cbd4b7789 | ||
|
fb03dd977e | ||
|
3c9490be22 | ||
|
d4016d8ec1 | ||
|
a45432b54d | ||
|
37ec04d518 | ||
|
4773d737b9 | ||
|
336e7addb6 | ||
|
2ef77b1833 | ||
|
df89f32b88 | ||
|
5ad467aa2c | ||
|
41edb3b9dd | ||
|
2797c0f216 | ||
|
ab694eccde | ||
|
74689b1f44 | ||
|
f85d8cb81a | ||
|
552a67acde | ||
|
c4f9d432dd | ||
|
21bb21b65b | ||
|
047bec1288 | ||
|
f4175b4b07 | ||
|
530baa23cd | ||
|
4c231d5b97 | ||
|
0f39e0124d | ||
|
0abb84fa39 | ||
|
06022e788e | ||
|
15f619ade0 | ||
|
1db19f4b2d | ||
|
f56b85b7dd | ||
|
2c59206b3e | ||
|
e794e5e5e4 | ||
|
18b02ce00e | ||
|
8da6b696ab | ||
|
d181511155 | ||
|
4296189283 | ||
|
d32346bae5 | ||
|
605cc4f736 | ||
|
4bbfa8d455 | ||
|
b6e3a22f7c | ||
|
5a01a4c8a9 | ||
|
40eccb0d6c | ||
|
5c07060ce0 | ||
|
9e05aa5962 | ||
|
a47adbcd0f | ||
|
2843b925f9 | ||
|
a2430a8cce | ||
|
6ebe6f2600 | ||
|
da9288878b | ||
|
7a9db57eaf | ||
|
589b5dca9e | ||
|
b99df0cf78 | ||
|
5c3b6e496c | ||
|
7658ffd71d | ||
|
66d86d0177 | ||
|
4f7e9ed3bb | ||
|
8dd4250d02 | ||
|
8b7e6f2e34 | ||
|
9cfa4bd7cc | ||
|
71f87a5864 | ||
|
aed7761a8d | ||
|
a16dbfd110 | ||
|
833313496c | ||
|
a180bde0fd | ||
|
02d9bfc2dd | ||
|
376a5cbbba | ||
|
03e2ecc9a5 | ||
|
ff5f647df0 | ||
|
e2a4559c03 | ||
|
d252d22343 | ||
|
a25aac7d67 | ||
|
332e9560ab | ||
|
7bebe97724 | ||
|
001d6ec2c9 | ||
|
99e8b4033e | ||
|
e08e606c82 | ||
|
d14eb7555d | ||
|
f1a11d41cb | ||
|
54307a4394 | ||
|
1ce0853ac5 | ||
|
38a74b42da | ||
|
684522807f | ||
|
0d6ef034d2 | ||
|
b1cec517ff | ||
|
62abf6ac1f | ||
|
4842ad1b6a | ||
|
959085c145 | ||
|
ea03e95174 | ||
|
3428cec194 | ||
|
b60fbf3374 | ||
|
6b73acc173 | ||
|
59430111bd | ||
|
29b6dd8ed2 | ||
|
c9e7b68a4c | ||
|
b7523f4b9f | ||
|
9882207c16 | ||
|
3f8ab538c1 | ||
|
15c613a9eb | ||
|
390daf7a92 | ||
|
34953774f3 | ||
|
4abfa28e08 | ||
|
22d206c1e0 | ||
|
2db0c0bf0a | ||
|
0618fa88e1 | ||
|
2d19f233ab | ||
|
2b34aa4291 | ||
|
bfce663a60 | ||
|
89d6ce7d43 | ||
|
069c701ebf | ||
|
b3d2753308 | ||
|
bf4c6e78d4 | ||
|
118543769f | ||
|
dd81eec2fd | ||
|
406988ba7b | ||
|
48a21aa0eb | ||
|
b79099f7ba | ||
|
59ae95b22f | ||
|
1355890f9f | ||
|
1fbe16a8d2 | ||
|
ee15731cbc | ||
|
cc3c89a11c | ||
|
a02bb79d87 | ||
|
614bd87b60 | ||
|
1ae812ea20 | ||
|
6ec6ddea9b | ||
|
f0095b4de2 | ||
|
5435b2c9f0 | ||
|
3bf611787a | ||
|
4ef0fc1ca0 | ||
|
52f4139674 | ||
|
9e328a9549 | ||
|
ebde56b932 | ||
|
c0d95cb967 | ||
|
b87699c034 | ||
|
fd7d3a7b92 | ||
|
8175f05c89 | ||
|
0ae3323bd2 | ||
|
03c2ef1787 | ||
|
9e56f54efb | ||
|
dc300aa4e0 | ||
|
751808c59b | ||
|
2a2b092864 | ||
|
cac89ae65d | ||
|
21fdf066b4 | ||
|
df60510db5 | ||
|
3e052376ac | ||
|
759fc6f42e | ||
|
d5f228dd00 | ||
|
78cdae6999 | ||
|
ae7a2b0dfa | ||
|
1142ee5fc1 | ||
|
2510456817 | ||
|
041b88f8bb | ||
|
e354331743 | ||
|
35c5be6ec2 | ||
|
0cb693700f | ||
|
b221aa2cf6 | ||
|
9407833a83 | ||
|
1fd268ae2b | ||
|
20d347a806 | ||
|
56946fac8f | ||
|
911b207fa1 | ||
|
d507cd851c | ||
|
c10f226622 | ||
|
99cf2c415f | ||
|
e7777cb1ee | ||
|
ca75300ae9 | ||
|
79de112d62 | ||
|
9e398c59ab | ||
|
3e51ba4d51 | ||
|
73f4835a53 | ||
|
2de5081829 | ||
|
2da473c8c8 | ||
|
58e0a698e3 | ||
|
11bfda92ba | ||
|
058424c16a | ||
|
eb88dfc4b4 | ||
|
f34f1562ff | ||
|
c6cafc9725 | ||
|
f8b3f38b57 | ||
|
b658915846 | ||
|
51f1aff162 | ||
|
3401ef56f8 | ||
|
4aea8dd65a | ||
|
354ae73ffb | ||
|
acf6582de4 | ||
|
5b616c503f | ||
|
1ca1583513 | ||
|
54d52c66fd | ||
|
c7acdd6006 | ||
|
5bf338ea88 | ||
|
72e66e4d67 | ||
|
dca4d7c027 | ||
|
0a10556548 | ||
|
9043df6be7 | ||
|
df584350b4 | ||
|
791d48c690 | ||
|
35a6d65e22 | ||
|
20d106d8a3 | ||
|
8b2ccccbe5 | ||
|
fd8adb32ce | ||
|
224168a28f | ||
|
a1b35bb44b | ||
|
ad282da97c | ||
|
101aff6c43 | ||
|
9f07d9edeb | ||
|
129890ab1b | ||
|
2051a79da3 | ||
|
dba9493a90 | ||
|
fa9d516ee2 | ||
|
2506d0b4f2 | ||
|
82475c232b | ||
|
5185cc9348 | ||
|
26830c3d2d | ||
|
e7af8d662b | ||
|
f8a03b096b | ||
|
1396f6886a | ||
|
563a20a040 | ||
|
bb7dcef19b | ||
|
281fc074ba | ||
|
292ead1fe0 | ||
|
5471f8a1d9 | ||
|
333f1ffb94 | ||
|
7069083b0f | ||
|
ce21454a43 | ||
|
e5fb9af0ea | ||
|
449ce6cc75 | ||
|
ed00e11cc5 | ||
|
33b86a8e53 | ||
|
cdc956a96c | ||
|
b1004a4733 | ||
|
86673a337a | ||
|
df92e57ad6 | ||
|
df4d16d2f1 | ||
|
7e4e6d2070 | ||
|
4464ce7270 | ||
|
a4334a8126 | ||
|
75f1998123 | ||
|
0b88583a10 | ||
|
070c32f4a6 | ||
|
b521160c92 | ||
|
b3083d83ae | ||
|
0e3bc2b1e0 | ||
|
a53e523f93 | ||
|
efc7c1d664 | ||
|
5bea22f321 | ||
|
c26ec5a3b8 | ||
|
a5d741aba4 | ||
|
f378f98a40 | ||
|
02eeb6fa00 | ||
|
94eb804abe | ||
|
c5be86a6db | ||
|
f9ccbad4d9 | ||
|
5b2abbed25 | ||
|
bce9df9b5e | ||
|
45082b3936 | ||
|
f4cf0260bf | ||
|
a780e80deb | ||
|
2d52c9e8bc | ||
|
f3bb5b9cdc | ||
|
b3beb15b00 | ||
|
7a84dc749c | ||
|
9c97946531 | ||
|
d0bb4d877f | ||
|
ba25869045 | ||
|
773f479719 | ||
|
217b0bf3af | ||
|
16ca0c24d3 | ||
|
1cb3fa2e81 | ||
|
c05998f5dd | ||
|
d1bab643ab | ||
|
6e0cb8a7aa | ||
|
47ee3fc9a9 | ||
|
b0d407fd63 | ||
|
3a762d9aac | ||
|
37b73ef46e | ||
|
dabf2216c3 | ||
|
380ac8e79d | ||
|
580bf45ccf | ||
|
0d5250cffa | ||
|
060a3b632f | ||
|
781890b7df | ||
|
00cd4ef864 | ||
|
ddc5cd7e4b | ||
|
53a0585dac | ||
|
6ea95b6ad1 | ||
|
605a624da6 | ||
|
1fa5bc31c0 | ||
|
c62e3ca764 | ||
|
f46c33e4e2 | ||
|
19b6091554 | ||
|
4916854492 | ||
|
2d9eee5d02 | ||
|
f651878df3 | ||
|
250479dc37 | ||
|
f0a5b958a1 | ||
|
761f56ef40 | ||
|
73f3325f80 | ||
|
9ce541e909 | ||
|
9716b1b6b7 | ||
|
655e803adf | ||
|
96001c5de6 | ||
|
cb206e4701 | ||
|
4632b5daae | ||
|
6b392a46ea | ||
|
88666629a7 | ||
|
c927053d4b | ||
|
c5d9144aef | ||
|
cdd53c7de9 | ||
|
e95e91ccf2 | ||
|
b824b33dc3 | ||
|
c4404f3d5d | ||
|
cba24464e8 | ||
|
2942590ee3 | ||
|
fdb4931475 | ||
|
b215375125 | ||
|
98e56e0327 | ||
|
d2977cff98 | ||
|
c8a9c856c2 | ||
|
e92016ac2e | ||
|
24a938abaa | ||
|
61e7a993bd | ||
|
9d149f2317 | ||
|
bc075212cb | ||
|
3875d3284e | ||
|
a0083f7f98 | ||
|
431f7dfa3d | ||
|
8812394ed8 | ||
|
010c8d4f08 | ||
|
67b5093ca5 | ||
|
a0a2c5cb37 | ||
|
f628db383a | ||
|
1c494e3d94 | ||
|
9bdd6125a1 | ||
|
fd017d00f9 | ||
|
90635c138f | ||
|
37ef62b0e6 | ||
|
aa12a5f967 | ||
|
846fe70cff | ||
|
d82519bf8a | ||
|
78da1a824f | ||
|
406e6a2f35 | ||
|
96885dd9a7 |
10
.github/ISSUE_TEMPLATE/1-issue.md
vendored
|
@ -1,10 +0,0 @@
|
|||
---
|
||||
name: Issue
|
||||
about: Please only raise an issue if you've been advised to do so after discussion. Thanks! 🙏
|
||||
---
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Raised initially as discussion #...
|
||||
- [ ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.)
|
||||
- [ ] I have reduced the issue to the simplest possible case.
|
6
.github/ISSUE_TEMPLATE/config.yml
vendored
|
@ -1,6 +0,0 @@
|
|||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Discussions
|
||||
url: https://github.com/encode/django-rest-framework/discussions
|
||||
about: >
|
||||
The "Discussions" forum is where you want to start. 💖
|
13
.github/dependabot.yml
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
# Keep GitHub Actions up to date with GitHub's Dependabot...
|
||||
# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
|
||||
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
groups:
|
||||
github-actions:
|
||||
patterns:
|
||||
- "*" # Group all Action updates into a single larger pull request
|
||||
schedule:
|
||||
interval: weekly
|
22
.github/stale.yml
vendored
Normal file
|
@ -0,0 +1,22 @@
|
|||
# Documentation: https://github.com/probot/stale
|
||||
|
||||
# Number of days of inactivity before an issue becomes stale
|
||||
daysUntilStale: 60
|
||||
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 7
|
||||
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed if no further activity occurs. Thank you
|
||||
for your contributions.
|
||||
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
closeComment: false
|
||||
|
||||
# Limit the number of actions per hour, from 1-30. Default is 30
|
||||
limitPerRun: 1
|
||||
|
||||
# Label to use when marking as stale
|
||||
staleLabel: stale
|
73
.github/workflows/main.yml
vendored
Normal file
|
@ -0,0 +1,73 @@
|
|||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: Python ${{ matrix.python-version }}
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
python-version:
|
||||
- '3.9'
|
||||
- '3.10'
|
||||
- '3.11'
|
||||
- '3.12'
|
||||
- '3.13'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'requirements/*.txt'
|
||||
|
||||
- name: Upgrade packaging tools
|
||||
run: python -m pip install --upgrade pip setuptools virtualenv wheel
|
||||
|
||||
- name: Install dependencies
|
||||
run: python -m pip install --upgrade tox
|
||||
|
||||
- name: Run tox targets for ${{ matrix.python-version }}
|
||||
run: tox run -f py$(echo ${{ matrix.python-version }} | tr -d . | cut -f 1 -d '-')
|
||||
|
||||
- name: Run extra tox targets
|
||||
if: ${{ matrix.python-version == '3.9' }}
|
||||
run: |
|
||||
tox -e base,dist,docs
|
||||
|
||||
- name: Upload coverage
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
env_vars: TOXENV,DJANGO
|
||||
|
||||
test-docs:
|
||||
name: Test documentation links
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.9'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements/requirements-documentation.txt
|
||||
|
||||
# Start mkdocs server and wait for it to be ready
|
||||
- run: mkdocs serve &
|
||||
- run: WAIT_TIME=0 && until nc -vzw 2 localhost 8000 || [ $WAIT_TIME -eq 5 ]; do sleep $(( WAIT_TIME++ )); done
|
||||
- run: if [ $WAIT_TIME == 5 ]; then echo cannot start mkdocs server on http://localhost:8000; exit 1; fi
|
||||
|
||||
- name: Check links
|
||||
continue-on-error: true
|
||||
run: pylinkvalidate.py -P http://localhost:8000/
|
||||
|
||||
- run: echo "Done"
|
22
.github/workflows/pre-commit.yml
vendored
Normal file
|
@ -0,0 +1,22 @@
|
|||
name: pre-commit
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
pre-commit:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
- uses: pre-commit/action@v3.0.1
|
4
.gitignore
vendored
|
@ -15,6 +15,6 @@
|
|||
MANIFEST
|
||||
coverage.*
|
||||
|
||||
!.github
|
||||
!.gitignore
|
||||
!.travis.yml
|
||||
!.isort.cfg
|
||||
!.pre-commit-config.yaml
|
||||
|
|
39
.pre-commit-config.yaml
Normal file
|
@ -0,0 +1,39 @@
|
|||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.5.0
|
||||
hooks:
|
||||
- id: check-added-large-files
|
||||
- id: check-case-conflict
|
||||
- id: check-json
|
||||
- id: check-merge-conflict
|
||||
- id: check-symlinks
|
||||
- id: check-toml
|
||||
- repo: https://github.com/pycqa/isort
|
||||
rev: 5.13.2
|
||||
hooks:
|
||||
- id: isort
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
rev: 7.0.0
|
||||
hooks:
|
||||
- id: flake8
|
||||
additional_dependencies:
|
||||
- flake8-tidy-imports
|
||||
- repo: https://github.com/adamchainz/blacken-docs
|
||||
rev: 1.16.0
|
||||
hooks:
|
||||
- id: blacken-docs
|
||||
exclude: ^(?!docs).*$
|
||||
additional_dependencies:
|
||||
- black==23.1.0
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
# Configuration for codespell is in .codespellrc
|
||||
rev: v2.2.6
|
||||
hooks:
|
||||
- id: codespell
|
||||
exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js
|
||||
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v3.19.1
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
args: ["--py39-plus", "--keep-percent-format"]
|
56
.travis.yml
|
@ -1,56 +0,0 @@
|
|||
language: python
|
||||
cache: pip
|
||||
dist: bionic
|
||||
matrix:
|
||||
fast_finish: true
|
||||
include:
|
||||
|
||||
- { python: "3.5", env: DJANGO=2.2 }
|
||||
|
||||
- { python: "3.6", env: DJANGO=2.2 }
|
||||
- { python: "3.6", env: DJANGO=3.0 }
|
||||
- { python: "3.6", env: DJANGO=3.1 }
|
||||
- { python: "3.6", env: DJANGO=3.2 }
|
||||
|
||||
- { python: "3.7", env: DJANGO=2.2 }
|
||||
- { python: "3.7", env: DJANGO=3.0 }
|
||||
- { python: "3.7", env: DJANGO=3.1 }
|
||||
- { python: "3.7", env: DJANGO=3.2 }
|
||||
|
||||
- { python: "3.8", env: DJANGO=3.0 }
|
||||
- { python: "3.8", env: DJANGO=3.1 }
|
||||
- { python: "3.8", env: DJANGO=3.2 }
|
||||
- { python: "3.8", env: DJANGO=main }
|
||||
|
||||
- { python: "3.9", env: DJANGO=3.1 }
|
||||
- { python: "3.9", env: DJANGO=3.2 }
|
||||
- { python: "3.9", env: DJANGO=main }
|
||||
|
||||
- { python: "3.8", env: TOXENV=base }
|
||||
- { python: "3.8", env: TOXENV=lint }
|
||||
- { python: "3.8", env: TOXENV=docs }
|
||||
|
||||
- python: "3.8"
|
||||
env: TOXENV=dist
|
||||
script:
|
||||
- python setup.py bdist_wheel
|
||||
- rm -r djangorestframework.egg-info # see #6139
|
||||
- tox --installpkg ./dist/djangorestframework-*.whl
|
||||
- tox # test sdist
|
||||
|
||||
allow_failures:
|
||||
- env: DJANGO=main
|
||||
- env: DJANGO=3.2
|
||||
|
||||
install:
|
||||
- pip install tox tox-travis
|
||||
|
||||
script:
|
||||
- tox
|
||||
|
||||
after_success:
|
||||
- pip install codecov
|
||||
- codecov -e TOXENV,DJANGO
|
||||
|
||||
notifications:
|
||||
email: false
|
206
CONTRIBUTING.md
|
@ -1,207 +1,5 @@
|
|||
# Contributing to REST framework
|
||||
|
||||
> The world can only really be changed one piece at a time. The art is picking that piece.
|
||||
>
|
||||
> — [Tim Berners-Lee][cite]
|
||||
At this point in its lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
|
||||
|
||||
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
|
||||
|
||||
## Community
|
||||
|
||||
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
|
||||
|
||||
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
|
||||
|
||||
Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
|
||||
|
||||
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
|
||||
|
||||
## Code of conduct
|
||||
|
||||
Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
|
||||
|
||||
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations. (e.g. 'Hey folks,')
|
||||
|
||||
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums.
|
||||
|
||||
# Issues
|
||||
|
||||
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
|
||||
|
||||
Some tips on good issue reporting:
|
||||
|
||||
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
|
||||
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bug fixes, and great documentation.
|
||||
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
|
||||
|
||||
## Triaging issues
|
||||
|
||||
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to:
|
||||
|
||||
* Read through the ticket - does it make sense, is it missing any context that would help explain it better?
|
||||
* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
|
||||
* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
|
||||
* If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?
|
||||
* If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.
|
||||
|
||||
# Development
|
||||
|
||||
To start developing on Django REST framework, clone the repo:
|
||||
|
||||
git clone https://github.com/encode/django-rest-framework
|
||||
|
||||
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
|
||||
|
||||
## Testing
|
||||
|
||||
To run the tests, clone the repository, and then:
|
||||
|
||||
# Setup the virtual environment
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
pip install django
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Run the tests
|
||||
./runtests.py
|
||||
|
||||
### Test options
|
||||
|
||||
Run using a more concise output style.
|
||||
|
||||
./runtests.py -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
./runtests.py --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
./runtests.py --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
./runtests.py --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
./runtests.py MyTestCase
|
||||
|
||||
Run the tests for a given test method.
|
||||
|
||||
./runtests.py MyTestCase.test_this_method
|
||||
|
||||
Shorter form to run the tests for a given test method.
|
||||
|
||||
./runtests.py test_this_method
|
||||
|
||||
Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input.
|
||||
|
||||
### Running against multiple environments
|
||||
|
||||
You can also use the excellent [tox][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
|
||||
|
||||
tox
|
||||
|
||||
## Pull requests
|
||||
|
||||
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
|
||||
|
||||
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests.
|
||||
|
||||
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
|
||||
|
||||
GitHub's documentation for working on pull requests is [available here][pull-requests].
|
||||
|
||||
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible on all supported versions of Python and Django.
|
||||
|
||||
Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
|
||||
|
||||
## Managing compatibility issues
|
||||
|
||||
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
|
||||
|
||||
# Documentation
|
||||
|
||||
The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
|
||||
|
||||
There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
|
||||
|
||||
## Building the documentation
|
||||
|
||||
To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
|
||||
|
||||
mkdocs build
|
||||
|
||||
This will build the documentation into the `site` directory.
|
||||
|
||||
You can build the documentation and open a preview in a browser window by using the `serve` command.
|
||||
|
||||
mkdocs serve
|
||||
|
||||
## Language style
|
||||
|
||||
Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
|
||||
|
||||
Some other tips:
|
||||
|
||||
* Keep paragraphs reasonably short.
|
||||
* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
|
||||
|
||||
## Markdown style
|
||||
|
||||
There are a couple of conventions you should follow when working on the documentation.
|
||||
|
||||
##### 1. Headers
|
||||
|
||||
Headers should use the hash style. For example:
|
||||
|
||||
### Some important topic
|
||||
|
||||
The underline style should not be used. **Don't do this:**
|
||||
|
||||
Some important topic
|
||||
====================
|
||||
|
||||
##### 2. Links
|
||||
|
||||
Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
|
||||
|
||||
Here is a link to [some other thing][other-thing].
|
||||
|
||||
More text...
|
||||
|
||||
[other-thing]: http://example.com/other/thing
|
||||
|
||||
This style helps keep the documentation source consistent and readable.
|
||||
|
||||
If you are hyperlinking to another REST framework document, you should use a relative link, and link to the `.md` suffix. For example:
|
||||
|
||||
[authentication]: ../api-guide/authentication.md
|
||||
|
||||
Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
|
||||
|
||||
##### 3. Notes
|
||||
|
||||
If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
|
||||
|
||||
---
|
||||
|
||||
**Note:** A useful documentation note.
|
||||
|
||||
---
|
||||
|
||||
|
||||
[cite]: https://www.w3.org/People/Berners-Lee/FAQ.html
|
||||
[code-of-conduct]: https://www.djangoproject.com/conduct/
|
||||
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
|
||||
[issues]: https://github.com/encode/django-rest-framework/issues?state=open
|
||||
[pep-8]: https://www.python.org/dev/peps/pep-0008/
|
||||
[pull-requests]: https://help.github.com/articles/using-pull-requests
|
||||
[tox]: https://tox.readthedocs.io/en/latest/
|
||||
[markdown]: https://daringfireball.net/projects/markdown/basics
|
||||
[docs]: https://github.com/encode/django-rest-framework/tree/master/docs
|
||||
[mou]: http://mouapp.com/
|
||||
The [Contributing guide in the documentation](https://www.django-rest-framework.org/community/contributing/) gives some more information on our process and code of conduct.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
include README.md
|
||||
include LICENSE.md
|
||||
recursive-include tests/* *
|
||||
recursive-include rest_framework/static *.js *.css *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
|
||||
recursive-include tests/ *
|
||||
recursive-include rest_framework/static *.js *.css *.map *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
|
||||
recursive-include rest_framework/templates *.html schema.js
|
||||
recursive-include rest_framework/locale *.mo
|
||||
global-exclude __pycache__
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
*Note*: Before submitting this pull request, please review our [contributing guidelines](https://github.com/encode/django-rest-framework/blob/master/CONTRIBUTING.md#pull-requests).
|
||||
*Note*: Before submitting a code change, please review our [contributing guidelines](https://www.django-rest-framework.org/community/contributing/#pull-requests).
|
||||
|
||||
## Description
|
||||
|
||||
|
|
65
README.md
|
@ -1,6 +1,6 @@
|
|||
# [Django REST framework][docs]
|
||||
|
||||
[![build-status-image]][travis]
|
||||
[![build-status-image]][build-status]
|
||||
[![coverage-status-image]][codecov]
|
||||
[![pypi-version]][pypi]
|
||||
|
||||
|
@ -21,12 +21,16 @@ The initial aim is to provide a single full-time position on REST framework.
|
|||
|
||||
[![][sentry-img]][sentry-url]
|
||||
[![][stream-img]][stream-url]
|
||||
[![][rollbar-img]][rollbar-url]
|
||||
[![][esg-img]][esg-url]
|
||||
[![][spacinov-img]][spacinov-url]
|
||||
[![][retool-img]][retool-url]
|
||||
[![][bitio-img]][bitio-url]
|
||||
[![][posthog-img]][posthog-url]
|
||||
[![][cryptapi-img]][cryptapi-url]
|
||||
[![][fezto-img]][fezto-url]
|
||||
[![][svix-img]][svix-url]
|
||||
[![][zuplo-img]][zuplo-url]
|
||||
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [ESG][esg-url], [Retool][retool-url], and [bit.io][bitio-url].
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Spacinov][spacinov-url], [Retool][retool-url], [bit.io][bitio-url], [PostHog][posthog-url], [CryptAPI][cryptapi-url], [FEZTO][fezto-url], [Svix][svix-url], and [Zuplo][zuplo-url].
|
||||
|
||||
---
|
||||
|
||||
|
@ -36,14 +40,12 @@ Django REST framework is a powerful and flexible toolkit for building Web APIs.
|
|||
|
||||
Some reasons you might want to use REST framework:
|
||||
|
||||
* The [Web browsable API][sandbox] is a huge usability win for your developers.
|
||||
* The Web browsable API is a huge usability win for your developers.
|
||||
* [Authentication policies][authentication] including optional packages for [OAuth1a][oauth1-section] and [OAuth2][oauth2-section].
|
||||
* [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources.
|
||||
* Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers].
|
||||
* [Extensive documentation][docs], and [great community support][group].
|
||||
|
||||
There is a live example API for testing purposes, [available here][sandbox].
|
||||
|
||||
**Below**: *Screenshot from the browsable API*
|
||||
|
||||
![Screenshot][image]
|
||||
|
@ -52,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox].
|
|||
|
||||
# Requirements
|
||||
|
||||
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
|
||||
* Django (2.2, 3.0, 3.1)
|
||||
* Python 3.9+
|
||||
* Django 4.2, 5.0, 5.1, 5.2
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
@ -65,11 +67,12 @@ Install using `pip`...
|
|||
pip install djangorestframework
|
||||
|
||||
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
|
||||
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
```python
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
```
|
||||
|
||||
# Example
|
||||
|
||||
|
@ -87,9 +90,10 @@ Startup up a new project like so...
|
|||
Now edit the `example/urls.py` module in your project:
|
||||
|
||||
```python
|
||||
from django.urls import path, include
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import serializers, viewsets, routers
|
||||
from django.urls import include, path
|
||||
from rest_framework import routers, serializers, viewsets
|
||||
|
||||
|
||||
# Serializers define the API representation.
|
||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
|
@ -108,7 +112,6 @@ class UserViewSet(viewsets.ModelViewSet):
|
|||
router = routers.DefaultRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
|
||||
|
||||
# Wire up our API using automatic URL routing.
|
||||
# Additionally, we include login URLs for the browsable API.
|
||||
urlpatterns = [
|
||||
|
@ -168,40 +171,44 @@ Or to create a new user:
|
|||
|
||||
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
|
||||
|
||||
For questions and support, use the [REST framework discussion group][group], or `#restframework` on freenode IRC.
|
||||
|
||||
You may also want to [follow the author on Twitter][twitter].
|
||||
For questions and support, use the [REST framework discussion group][group], or `#restframework` on libera.chat IRC.
|
||||
|
||||
# Security
|
||||
|
||||
Please see the [security policy][security-policy].
|
||||
|
||||
[build-status-image]: https://secure.travis-ci.org/encode/django-rest-framework.svg?branch=master
|
||||
[travis]: https://travis-ci.org/encode/django-rest-framework?branch=master
|
||||
[build-status-image]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml/badge.svg
|
||||
[build-status]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml
|
||||
[coverage-status-image]: https://img.shields.io/codecov/c/github/encode/django-rest-framework/master.svg
|
||||
[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master
|
||||
[pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
|
||||
[pypi]: https://pypi.org/project/djangorestframework/
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
|
||||
[funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
|
||||
[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/sentry-readme.png
|
||||
[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/stream-readme.png
|
||||
[rollbar-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rollbar-readme.png
|
||||
[esg-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/esg-readme.png
|
||||
[spacinov-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/spacinov-readme.png
|
||||
[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/retool-readme.png
|
||||
[bitio-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/bitio-readme.png
|
||||
[posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/posthog-readme.png
|
||||
[cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png
|
||||
[fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/fezto-readme.png
|
||||
[svix-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/svix-premium.png
|
||||
[zuplo-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/zuplo-readme.png
|
||||
|
||||
[sentry-url]: https://getsentry.com/welcome/
|
||||
[stream-url]: https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf
|
||||
[rollbar-url]: https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial
|
||||
[esg-url]: https://software.esg-usa.com/
|
||||
[stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage
|
||||
[spacinov-url]: https://www.spacinov.com/
|
||||
[retool-url]: https://retool.com/?utm_source=djangorest&utm_medium=sponsorship
|
||||
[bitio-url]: https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship
|
||||
[posthog-url]: https://posthog.com?utm_source=drf&utm_medium=sponsorship&utm_campaign=open-source-sponsorship
|
||||
[cryptapi-url]: https://cryptapi.io
|
||||
[fezto-url]: https://www.fezto.xyz/?utm_source=DjangoRESTFramework
|
||||
[svix-url]: https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship
|
||||
[zuplo-url]: https://zuplo.link/django-gh
|
||||
|
||||
[oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
|
||||
[oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
|
||||
|
|
|
@ -2,8 +2,6 @@
|
|||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you believe you've found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
**Please report security issues by emailing security@encode.io**.
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
|
|
@ -11,9 +11,9 @@ source:
|
|||
|
||||
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
|
||||
|
||||
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
|
||||
REST framework provides several authentication schemes out of the box, and also allows you to implement custom schemes.
|
||||
|
||||
Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
|
||||
Authentication always runs at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
|
||||
|
||||
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
|
||||
|
||||
|
@ -23,7 +23,7 @@ The `request.auth` property is used for any additional authentication informatio
|
|||
|
||||
**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
|
||||
|
||||
For information on how to setup the permission polices for your API please see the [permissions documentation][permission].
|
||||
For information on how to set up the permission policies for your API please see the [permissions documentation][permission].
|
||||
|
||||
---
|
||||
|
||||
|
@ -90,6 +90,12 @@ The kind of response that will be used depends on the authentication scheme. Al
|
|||
|
||||
Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme.
|
||||
|
||||
## Django 5.1+ `LoginRequiredMiddleware`
|
||||
|
||||
If you're running Django 5.1+ and use the [`LoginRequiredMiddleware`][login-required-middleware], please note that all views from DRF are opted-out of this middleware. This is because the authentication in DRF is based authentication and permissions classes, which may be determined after the middleware has been applied. Additionally, when the request is not authenticated, the middleware redirects the user to the login page, which is not suitable for API requests, where it's preferable to return a 401 status code.
|
||||
|
||||
REST framework offers an equivalent mechanism for DRF views via the global settings, `DEFAULT_AUTHENTICATION_CLASSES` and `DEFAULT_PERMISSION_CLASSES`. They should be changed accordingly if you need to enforce that API requests are logged in.
|
||||
|
||||
## Apache mod_wsgi specific configuration
|
||||
|
||||
Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.
|
||||
|
@ -120,6 +126,14 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
|
|||
|
||||
## TokenAuthentication
|
||||
|
||||
---
|
||||
|
||||
**Note:** The token authentication provided by Django REST framework is a fairly simple implementation.
|
||||
|
||||
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the [Django REST Knox][django-rest-knox] third party package.
|
||||
|
||||
---
|
||||
|
||||
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
|
||||
|
||||
To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
|
||||
|
@ -129,11 +143,9 @@ To use the `TokenAuthentication` scheme you'll need to [configure the authentica
|
|||
'rest_framework.authtoken'
|
||||
]
|
||||
|
||||
---
|
||||
Make sure to run `manage.py migrate` after changing your settings.
|
||||
|
||||
**Note:** Make sure to run `manage.py migrate` after changing your settings. The `rest_framework.authtoken` app provides Django database migrations.
|
||||
|
||||
---
|
||||
The `rest_framework.authtoken` app provides Django database migrations.
|
||||
|
||||
You'll also need to create tokens for your users.
|
||||
|
||||
|
@ -146,7 +158,7 @@ For clients to authenticate, the token key should be included in the `Authorizat
|
|||
|
||||
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
|
||||
|
||||
**Note:** If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.
|
||||
*If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.*
|
||||
|
||||
If successfully authenticated, `TokenAuthentication` provides the following credentials.
|
||||
|
||||
|
@ -167,9 +179,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
|
|||
|
||||
---
|
||||
|
||||
#### Generating Tokens
|
||||
### Generating Tokens
|
||||
|
||||
##### By using signals
|
||||
#### By using signals
|
||||
|
||||
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
|
||||
|
||||
|
@ -193,7 +205,7 @@ If you've already created some users, you can generate tokens for all existing u
|
|||
for user in User.objects.all():
|
||||
Token.objects.get_or_create(user=user)
|
||||
|
||||
##### By exposing an api endpoint
|
||||
#### By exposing an api endpoint
|
||||
|
||||
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
|
||||
|
||||
|
@ -210,7 +222,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
|||
|
||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
||||
|
||||
By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
and include them using the `throttle_classes` attribute.
|
||||
|
||||
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||
|
@ -242,9 +254,9 @@ And in your `urls.py`:
|
|||
]
|
||||
|
||||
|
||||
##### With Django admin
|
||||
#### With Django admin
|
||||
|
||||
It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
|
||||
`your_app/admin.py`:
|
||||
|
||||
|
@ -279,11 +291,11 @@ If successfully authenticated, `SessionAuthentication` provides the following cr
|
|||
|
||||
Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
|
||||
|
||||
If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
|
||||
If you're using an AJAX-style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
|
||||
|
||||
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
||||
|
||||
CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
|
||||
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.
|
||||
|
||||
|
||||
## RemoteUserAuthentication
|
||||
|
@ -293,7 +305,7 @@ environment variable.
|
|||
|
||||
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
|
||||
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
|
||||
already exist. To change this and other behaviour, consult the
|
||||
already exist. To change this and other behavior, consult the
|
||||
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
||||
|
||||
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
||||
|
@ -301,7 +313,7 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following
|
|||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
Consult your web server's documentation for information about configuring an authentication method, e.g.:
|
||||
Consult your web server's documentation for information about configuring an authentication method, for example:
|
||||
|
||||
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
|
||||
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
|
||||
|
@ -316,7 +328,7 @@ In some circumstances instead of returning `None`, you may want to raise an `Aut
|
|||
Typically the approach you should take is:
|
||||
|
||||
* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
|
||||
* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
|
||||
* If authentication is attempted but fails, raise an `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
|
||||
|
||||
You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
|
||||
|
||||
|
@ -332,7 +344,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
|
|||
|
||||
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import authentication
|
||||
from rest_framework import exceptions
|
||||
|
||||
|
@ -353,13 +365,17 @@ The following example will authenticate any incoming request as the user given b
|
|||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
The following third-party packages are also available.
|
||||
|
||||
## django-rest-knox
|
||||
|
||||
[Django-rest-knox][django-rest-knox] library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
|
||||
|
||||
## Django OAuth Toolkit
|
||||
|
||||
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
|
||||
|
||||
#### Installation & configuration
|
||||
### Installation & configuration
|
||||
|
||||
Install using `pip`.
|
||||
|
||||
|
@ -384,9 +400,9 @@ For more details see the [Django REST framework - Getting started][django-oauth-
|
|||
|
||||
The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework.
|
||||
|
||||
This package was previously included directly in REST framework but is now supported and maintained as a third party package.
|
||||
This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.
|
||||
|
||||
#### Installation & configuration
|
||||
### Installation & configuration
|
||||
|
||||
Install the package using `pip`.
|
||||
|
||||
|
@ -404,11 +420,11 @@ The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y
|
|||
|
||||
## HTTP Signature Authentication
|
||||
|
||||
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig].
|
||||
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy-to-use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig].
|
||||
|
||||
## Djoser
|
||||
|
||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.
|
||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
|
||||
|
||||
## django-rest-auth / dj-rest-auth
|
||||
|
||||
|
@ -420,21 +436,17 @@ There are currently two forks of this project.
|
|||
* [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
|
||||
* [Dj-rest-auth][dj-rest-auth] is a newer fork of the project.
|
||||
|
||||
## django-rest-framework-social-oauth2
|
||||
## drf-social-oauth2
|
||||
|
||||
[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2] library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.
|
||||
|
||||
## django-rest-knox
|
||||
|
||||
[Django-rest-knox][django-rest-knox] library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
|
||||
[Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
|
||||
|
||||
## drfpasswordless
|
||||
|
||||
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's own TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
|
||||
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
|
||||
|
||||
## django-rest-authemail
|
||||
|
||||
[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully-functional example project and detailed instructions are included.
|
||||
[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.
|
||||
|
||||
## Django-Rest-Durin
|
||||
|
||||
|
@ -442,13 +454,19 @@ There are currently two forks of this project.
|
|||
|
||||
More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html).
|
||||
|
||||
## django-pyoidc
|
||||
|
||||
[dango-pyoidc][django_pyoidc] adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc.
|
||||
|
||||
More information can be found in the [Documentation](https://django-pyoidc.readthedocs.io/latest/index.html).
|
||||
|
||||
[cite]: https://jacobian.org/writing/rest-worst-practices/
|
||||
[http401]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
|
||||
[http403]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
|
||||
[basicauth]: https://tools.ietf.org/html/rfc2617
|
||||
[permission]: permissions.md
|
||||
[throttling]: throttling.md
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax
|
||||
[mod_wsgi_official]: https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIPassAuthorization.html
|
||||
[django-oauth-toolkit-getting-started]: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html
|
||||
[django-rest-framework-oauth]: https://jpadilla.github.io/django-rest-framework-oauth/
|
||||
|
@ -473,8 +491,10 @@ More information can be found in the [Documentation](https://django-rest-durin.r
|
|||
[djoser]: https://github.com/sunscrapers/djoser
|
||||
[django-rest-auth]: https://github.com/Tivix/django-rest-auth
|
||||
[dj-rest-auth]: https://github.com/jazzband/dj-rest-auth
|
||||
[django-rest-framework-social-oauth2]: https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
|
||||
[drf-social-oauth2]: https://github.com/wagnerdelima/drf-social-oauth2
|
||||
[django-rest-knox]: https://github.com/James1345/django-rest-knox
|
||||
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
|
||||
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
|
||||
[django-rest-durin]: https://github.com/eshaan7/django-rest-durin
|
||||
[login-required-middleware]: https://docs.djangoproject.com/en/stable/ref/middleware/#django.contrib.auth.middleware.LoginRequiredMiddleware
|
||||
[django-pyoidc] : https://github.com/makinacorpus/django_pyoidc
|
||||
|
|
|
@ -28,37 +28,60 @@ from rest_framework import viewsets
|
|||
|
||||
class UserViewSet(viewsets.ViewSet):
|
||||
# With cookie: cache requested url for each user for 2 hours
|
||||
@method_decorator(cache_page(60*60*2))
|
||||
@method_decorator(cache_page(60 * 60 * 2))
|
||||
@method_decorator(vary_on_cookie)
|
||||
def list(self, request, format=None):
|
||||
content = {
|
||||
'user_feed': request.user.get_user_feed()
|
||||
"user_feed": request.user.get_user_feed(),
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
|
||||
class ProfileView(APIView):
|
||||
# With auth: cache requested url for each user for 2 hours
|
||||
@method_decorator(cache_page(60*60*2))
|
||||
@method_decorator(vary_on_headers("Authorization",))
|
||||
@method_decorator(cache_page(60 * 60 * 2))
|
||||
@method_decorator(vary_on_headers("Authorization"))
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
'user_feed': request.user.get_user_feed()
|
||||
"user_feed": request.user.get_user_feed(),
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
|
||||
class PostView(APIView):
|
||||
# Cache page for the requested url
|
||||
@method_decorator(cache_page(60*60*2))
|
||||
@method_decorator(cache_page(60 * 60 * 2))
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
'title': 'Post title',
|
||||
'body': 'Post content'
|
||||
"title": "Post title",
|
||||
"body": "Post content",
|
||||
}
|
||||
return Response(content)
|
||||
```
|
||||
|
||||
|
||||
## Using cache with @api_view decorator
|
||||
|
||||
When using @api_view decorator, the Django-provided method-based cache decorators such as [`cache_page`][page],
|
||||
[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers] can be called directly.
|
||||
|
||||
```python
|
||||
from django.views.decorators.cache import cache_page
|
||||
from django.views.decorators.vary import vary_on_cookie
|
||||
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
|
||||
|
||||
@cache_page(60 * 15)
|
||||
@vary_on_cookie
|
||||
@api_view(["GET"])
|
||||
def get_user_list(request):
|
||||
content = {"user_feed": request.user.get_user_feed()}
|
||||
return Response(content)
|
||||
```
|
||||
|
||||
|
||||
**NOTE:** The [`cache_page`][page] decorator only caches the
|
||||
`GET` and `HEAD` responses with status 200.
|
||||
|
||||
|
|
|
@ -82,7 +82,7 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO
|
|||
|
||||
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views.
|
||||
|
||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
|
|
@ -101,7 +101,7 @@ Note that the exception handler will only be called for responses generated by r
|
|||
|
||||
The **base class** for all exceptions raised inside an `APIView` class or `@api_view`.
|
||||
|
||||
To provide a custom exception, subclass `APIException` and set the `.status_code`, `.default_detail`, and `default_code` attributes on the class.
|
||||
To provide a custom exception, subclass `APIException` and set the `.status_code`, `.default_detail`, and `.default_code` attributes on the class.
|
||||
|
||||
For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:
|
||||
|
||||
|
@ -179,7 +179,7 @@ By default this exception results in a response with the HTTP status code "403 F
|
|||
|
||||
**Signature:** `NotFound(detail=None, code=None)`
|
||||
|
||||
Raised when a resource does not exists at the given URL. This exception is equivalent to the standard `Http404` Django exception.
|
||||
Raised when a resource does not exist at the given URL. This exception is equivalent to the standard `Http404` Django exception.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "404 Not Found".
|
||||
|
||||
|
@ -217,11 +217,10 @@ By default this exception results in a response with the HTTP status code "429 T
|
|||
|
||||
## ValidationError
|
||||
|
||||
**Signature:** `ValidationError(detail, code=None)`
|
||||
**Signature:** `ValidationError(detail=None, code=None)`
|
||||
|
||||
The `ValidationError` exception is slightly different from the other `APIException` classes:
|
||||
|
||||
* The `detail` argument is mandatory, not optional.
|
||||
* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the `validate()` method of a serializer. For example. `raise serializers.ValidationError({'name': 'Please enter a valid name.'})`
|
||||
* By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')`
|
||||
|
||||
|
@ -260,6 +259,15 @@ Set as `handler400`:
|
|||
|
||||
handler400 = 'rest_framework.exceptions.bad_request'
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third-party packages are also available.
|
||||
|
||||
## DRF Standardized Errors
|
||||
|
||||
The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
|
||||
|
||||
[cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/
|
||||
[authentication]: authentication.md
|
||||
[django-custom-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
|
|
|
@ -42,11 +42,11 @@ Set to false if this field is not required to be present during deserialization.
|
|||
|
||||
Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
|
||||
|
||||
Defaults to `True`.
|
||||
Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer) default value will be `False` if you have specified `blank=True` or `default` or `null=True` at your field in your `Model`.
|
||||
|
||||
### `default`
|
||||
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
|
||||
|
||||
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
|
||||
|
||||
|
@ -78,7 +78,14 @@ Defaults to `False`
|
|||
|
||||
### `source`
|
||||
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal.
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
|
||||
|
||||
When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example:
|
||||
|
||||
class CommentSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField(source="user.email")
|
||||
|
||||
This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
||||
|
||||
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
||||
|
||||
|
@ -144,7 +151,7 @@ Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
|
|||
since Django 2.1 default `serializers.BooleanField` instances will be generated
|
||||
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
|
||||
previous versions of Django, default `BooleanField` instances will be generated
|
||||
with a `required=False` option. If you want to control this behaviour manually,
|
||||
with a `required=False` option. If you want to control this behavior manually,
|
||||
explicitly declare the `BooleanField` on the serializer class, or use the
|
||||
`extra_kwargs` option to set the `required` flag.
|
||||
|
||||
|
@ -152,14 +159,6 @@ Corresponds to `django.db.models.fields.BooleanField`.
|
|||
|
||||
**Signature:** `BooleanField()`
|
||||
|
||||
## NullBooleanField
|
||||
|
||||
A boolean representation that also accepts `None` as a valid value.
|
||||
|
||||
Corresponds to `django.db.models.fields.NullBooleanField`.
|
||||
|
||||
**Signature:** `NullBooleanField()`
|
||||
|
||||
---
|
||||
|
||||
# String fields
|
||||
|
@ -172,10 +171,10 @@ Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T
|
|||
|
||||
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
|
||||
|
||||
- `max_length` - Validates that the input contains no more than this number of characters.
|
||||
- `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||
* `max_length` - Validates that the input contains no more than this number of characters.
|
||||
* `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||
|
||||
The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
|
||||
|
||||
|
@ -223,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
|
|||
|
||||
**Signature:** `UUIDField(format='hex_verbose')`
|
||||
|
||||
- `format`: Determines the representation format of the uuid value
|
||||
- `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
- `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||
- `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||
- `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
* `format`: Determines the representation format of the uuid value
|
||||
* `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
* `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||
* `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||
* `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
|
||||
|
||||
## FilePathField
|
||||
|
@ -238,11 +237,11 @@ Corresponds to `django.forms.fields.FilePathField`.
|
|||
|
||||
**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
|
||||
|
||||
- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||
- `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||
- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||
- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||
- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||
* `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||
* `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||
* `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||
* `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||
* `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||
|
||||
## IPAddressField
|
||||
|
||||
|
@ -252,8 +251,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
|
|||
|
||||
**Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
|
||||
|
||||
- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
||||
- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||
* `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case-insensitive.
|
||||
* `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||
|
||||
---
|
||||
|
||||
|
@ -267,8 +266,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.
|
|||
|
||||
**Signature**: `IntegerField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
|
||||
## FloatField
|
||||
|
||||
|
@ -278,8 +277,8 @@ Corresponds to `django.db.models.fields.FloatField`.
|
|||
|
||||
**Signature**: `FloatField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
|
||||
## DecimalField
|
||||
|
||||
|
@ -289,13 +288,14 @@ Corresponds to `django.db.models.fields.DecimalField`.
|
|||
|
||||
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
|
||||
|
||||
- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||
- `decimal_places` The number of decimal places to store with the number.
|
||||
- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||
- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||
* `decimal_places` The number of decimal places to store with the number.
|
||||
* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||
* `max_value` Validate that the number provided is no greater than this value. Should be an integer or `Decimal` object.
|
||||
* `min_value` Validate that the number provided is no less than this value. Should be an integer or `Decimal` object.
|
||||
* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||
* `rounding` Sets the rounding mode used when quantizing to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
* `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without losing data. Defaults to `False`.
|
||||
|
||||
#### Example usage
|
||||
|
||||
|
@ -307,10 +307,6 @@ And to validate numbers up to anything less than one billion with a resolution o
|
|||
|
||||
serializers.DecimalField(max_digits=19, decimal_places=10)
|
||||
|
||||
This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
|
||||
|
||||
If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
|
||||
|
||||
---
|
||||
|
||||
# Date and time fields
|
||||
|
@ -325,13 +321,13 @@ Corresponds to `django.db.models.fields.DateTimeField`.
|
|||
|
||||
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
* `default_timezone` - A `pytz.timezone` representing the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive.
|
||||
* `default_timezone` - A `tzinfo` subclass (`zoneinfo` or `pytz`) representing the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive.
|
||||
|
||||
#### `DateTimeField` format strings.
|
||||
|
||||
Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)
|
||||
|
||||
When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will determined by the renderer class.
|
||||
When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will be determined by the renderer class.
|
||||
|
||||
#### `auto_now` and `auto_now_add` model fields.
|
||||
|
||||
|
@ -385,8 +381,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu
|
|||
|
||||
**Signature:** `DurationField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the duration provided is no greater than this value.
|
||||
- `min_value` Validate that the duration provided is no less than this value.
|
||||
* `max_value` Validate that the duration provided is no greater than this value.
|
||||
* `min_value` Validate that the duration provided is no less than this value.
|
||||
|
||||
---
|
||||
|
||||
|
@ -400,10 +396,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding
|
|||
|
||||
**Signature:** `ChoiceField(choices)`
|
||||
|
||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||
|
||||
|
@ -413,10 +409,10 @@ A field that can accept a set of zero, one or many values, chosen from a limited
|
|||
|
||||
**Signature:** `MultipleChoiceField(choices)`
|
||||
|
||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||
|
||||
|
@ -437,9 +433,9 @@ Corresponds to `django.forms.fields.FileField`.
|
|||
|
||||
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
|
||||
- `max_length` - Designates the maximum length for the file name.
|
||||
- `allow_empty_file` - Designates if empty files are allowed.
|
||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
* `max_length` - Designates the maximum length for the file name.
|
||||
* `allow_empty_file` - Designates if empty files are allowed.
|
||||
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
|
||||
## ImageField
|
||||
|
||||
|
@ -449,9 +445,9 @@ Corresponds to `django.forms.fields.ImageField`.
|
|||
|
||||
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
|
||||
- `max_length` - Designates the maximum length for the file name.
|
||||
- `allow_empty_file` - Designates if empty files are allowed.
|
||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
* `max_length` - Designates the maximum length for the file name.
|
||||
* `allow_empty_file` - Designates if empty files are allowed.
|
||||
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
|
||||
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
|
||||
|
||||
|
@ -465,10 +461,10 @@ A field class that validates a list of objects.
|
|||
|
||||
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
|
||||
|
||||
- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
||||
- `allow_empty` - Designates if empty lists are allowed.
|
||||
- `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||
- `max_length` - Validates that the list contains no more than this number of elements.
|
||||
* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
||||
* `allow_empty` - Designates if empty lists are allowed.
|
||||
* `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||
* `max_length` - Validates that the list contains no more than this number of elements.
|
||||
|
||||
For example, to validate a list of integers you might use something like the following:
|
||||
|
||||
|
@ -489,8 +485,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar
|
|||
|
||||
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||
|
||||
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
|
||||
- `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
|
||||
* `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
|
||||
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
|
||||
|
||||
|
@ -507,8 +503,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie
|
|||
|
||||
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||
|
||||
- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
|
||||
- `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
|
||||
* `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
|
||||
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
|
||||
|
||||
|
@ -518,8 +514,8 @@ A field class that validates that the incoming data structure consists of valid
|
|||
|
||||
**Signature**: `JSONField(binary, encoder)`
|
||||
|
||||
- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
|
||||
- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
|
||||
* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
|
||||
* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
|
||||
|
||||
---
|
||||
|
||||
|
@ -554,6 +550,12 @@ The `HiddenField` class is usually only needed if you have some validation that
|
|||
|
||||
For further examples on `HiddenField` see the [validators](validators.md) documentation.
|
||||
|
||||
---
|
||||
|
||||
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
|
||||
|
||||
---
|
||||
|
||||
## ModelField
|
||||
|
||||
A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
|
||||
|
@ -570,7 +572,7 @@ This is a read-only field. It gets its value by calling a method on the serializ
|
|||
|
||||
**Signature**: `SerializerMethodField(method_name=None)`
|
||||
|
||||
- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||
* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||
|
||||
The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
|
||||
|
||||
|
@ -776,7 +778,7 @@ Here the mapping between the target and source attribute pairs (`x` and
|
|||
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
|
||||
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
|
||||
|
||||
Our new `DataPointSerializer` exhibits the same behaviour as the custom field
|
||||
Our new `DataPointSerializer` exhibits the same behavior as the custom field
|
||||
approach.
|
||||
|
||||
Serializing:
|
||||
|
@ -836,7 +838,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi
|
|||
|
||||
## django-rest-framework-gis
|
||||
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
|
||||
## django-rest-framework-hstore
|
||||
|
||||
|
@ -855,3 +857,4 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide
|
|||
[django-hstore]: https://github.com/djangonauts/django-hstore
|
||||
[python-decimal-rounding-modes]: https://docs.python.org/3/library/decimal.html#rounding-modes
|
||||
[django-current-timezone]: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#default-time-zone-and-current-time-zone
|
||||
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
|
|
|
@ -213,19 +213,23 @@ This will allow the client to filter the items in the list by making queries suc
|
|||
You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:
|
||||
|
||||
search_fields = ['username', 'email', 'profile__profession']
|
||||
|
||||
|
||||
For [JSONField][JSONField] and [HStoreField][HStoreField] fields you can filter based on nested values within the data structure using the same double-underscore notation:
|
||||
|
||||
search_fields = ['data__breed', 'data__owner__other_pets__0__name']
|
||||
|
||||
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.
|
||||
By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. Searches may contain _quoted phrases_ with spaces, each phrase is considered as a single search term.
|
||||
|
||||
The search behavior may be restricted by prepending various characters to the `search_fields`.
|
||||
|
||||
* '^' Starts-with search.
|
||||
* '=' Exact matches.
|
||||
* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend](https://docs.djangoproject.com/en/dev/ref/contrib/postgres/search/).)
|
||||
* '$' Regex search.
|
||||
The search behavior may be specified by prefixing field names in `search_fields` with one of the following characters (which is equivalent to adding `__<lookup>` to the field):
|
||||
|
||||
| Prefix | Lookup | |
|
||||
| ------ | --------------| ------------------ |
|
||||
| `^` | `istartswith` | Starts-with search.|
|
||||
| `=` | `iexact` | Exact matches. |
|
||||
| `$` | `iregex` | Regex search. |
|
||||
| `@` | `search` | Full-text search (Currently only supported Django's [PostgreSQL backend][postgres-search]). |
|
||||
| None | `icontains` | Contains search (Default). |
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -241,7 +245,7 @@ To dynamically change search fields based on request content, it's possible to s
|
|||
def get_search_fields(self, view, request):
|
||||
if request.query_params.get('title_only'):
|
||||
return ['title']
|
||||
return super(CustomSearchFilter, self).get_search_fields(view, request)
|
||||
return super().get_search_fields(view, request)
|
||||
|
||||
For more details, see the [Django documentation][search-django-admin].
|
||||
|
||||
|
@ -253,7 +257,7 @@ The `OrderingFilter` class supports simple query parameter controlled ordering o
|
|||
|
||||

|
||||
|
||||
By default, the query parameter is named `'ordering'`, but this may by overridden with the `ORDERING_PARAM` setting.
|
||||
By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting.
|
||||
|
||||
For example, to order users by username:
|
||||
|
||||
|
@ -269,7 +273,7 @@ Multiple orderings may also be specified:
|
|||
|
||||
### Specifying which fields may be ordered against
|
||||
|
||||
It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so:
|
||||
It's recommended that you explicitly specify which fields the API should allow in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so:
|
||||
|
||||
class UserListView(generics.ListAPIView):
|
||||
queryset = User.objects.all()
|
||||
|
@ -335,15 +339,6 @@ Generic filters may also present an interface in the browsable API. To do so you
|
|||
|
||||
The method should return a rendered HTML string.
|
||||
|
||||
## Pagination & schemas
|
||||
|
||||
You can also make the filter controls available to the schema autogeneration
|
||||
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
|
||||
|
||||
`get_schema_fields(self, view)`
|
||||
|
||||
The method should return a list of `coreapi.Field` instances.
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages provide additional filter implementations.
|
||||
|
@ -374,3 +369,4 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
|
|||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||
[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield
|
||||
[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield
|
||||
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/
|
||||
|
|
|
@ -23,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac
|
|||
Arguments:
|
||||
|
||||
* **urlpatterns**: Required. A URL pattern list.
|
||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||
|
||||
Example:
|
||||
|
||||
|
@ -62,7 +62,7 @@ Also note that `format_suffix_patterns` does not support descending into `includ
|
|||
|
||||
If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example:
|
||||
|
||||
url patterns = [
|
||||
urlpatterns = [
|
||||
…
|
||||
]
|
||||
|
||||
|
|
|
@ -65,7 +65,7 @@ The following attributes control the basic view behavior.
|
|||
|
||||
* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests.
|
||||
* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
|
||||
* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_field` - The model field that should be used for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`.
|
||||
|
||||
**Pagination**:
|
||||
|
@ -96,6 +96,12 @@ For example:
|
|||
user = self.request.user
|
||||
return user.accounts.all()
|
||||
|
||||
---
|
||||
|
||||
**Note:** If the `serializer_class` used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
||||
|
||||
---
|
||||
|
||||
#### `get_object(self)`
|
||||
|
||||
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
|
||||
|
@ -211,7 +217,7 @@ If the request data provided for creating the object was invalid, a `400 Bad Req
|
|||
|
||||
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
||||
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise, it will return a `404 Not Found`.
|
||||
|
||||
## UpdateModelMixin
|
||||
|
||||
|
@ -329,7 +335,7 @@ For example, if you need to lookup objects based on multiple fields in the URL c
|
|||
queryset = self.filter_queryset(queryset) # Apply any filter backends
|
||||
filter = {}
|
||||
for field in self.lookup_fields:
|
||||
if self.kwargs[field]: # Ignore empty fields.
|
||||
if self.kwargs.get(field): # Ignore empty fields.
|
||||
filter[field] = self.kwargs[field]
|
||||
obj = get_object_or_404(queryset, **filter) # Lookup the object
|
||||
self.check_object_permissions(self.request, obj)
|
||||
|
@ -389,3 +395,4 @@ The following third party packages provide additional generic view implementatio
|
|||
[UpdateModelMixin]: #updatemodelmixin
|
||||
[DestroyModelMixin]: #destroymodelmixin
|
||||
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
||||
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
|
|
|
@ -78,7 +78,7 @@ This pagination style accepts a single number page number in the request query p
|
|||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?page=5",
|
||||
"previous": "https://api.example.org/accounts/?page=3",
|
||||
"results": [
|
||||
|
@ -126,7 +126,7 @@ This pagination style mirrors the syntax used when looking up multiple database
|
|||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?limit=100&offset=500",
|
||||
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
|
||||
"results": [
|
||||
|
@ -218,16 +218,16 @@ To set these attributes you should override the `CursorPagination` class, and th
|
|||
|
||||
# Custom pagination styles
|
||||
|
||||
To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view=None)` and `get_paginated_response(self, data)` methods:
|
||||
To create a custom pagination serializer class, you should inherit the subclass `pagination.BasePagination`, override the `paginate_queryset(self, queryset, request, view=None)`, and `get_paginated_response(self, data)` methods:
|
||||
|
||||
* The `paginate_queryset` method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.
|
||||
* The `get_paginated_response` method is passed the serialized page data and should return a `Response` instance.
|
||||
* The `paginate_queryset` method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page.
|
||||
* The `get_paginated_response` method is passed to the serialized page data and should return a `Response` instance.
|
||||
|
||||
Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method.
|
||||
|
||||
## Example
|
||||
|
||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||
|
||||
class CustomPagination(pagination.PageNumberPagination):
|
||||
def get_paginated_response(self, data):
|
||||
|
@ -240,7 +240,7 @@ Suppose we want to replace the default pagination output style with a modified f
|
|||
'results': data
|
||||
})
|
||||
|
||||
We'd then need to setup the custom class in our configuration:
|
||||
We'd then need to set up the custom class in our configuration:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',
|
||||
|
@ -262,16 +262,7 @@ API responses for list endpoints will now include a `Link` header, instead of in
|
|||
|
||||
![Link Header][link-header]
|
||||
|
||||
*A custom pagination style, using the 'Link' header'*
|
||||
|
||||
## Pagination & schemas
|
||||
|
||||
You can also make the pagination controls available to the schema autogeneration
|
||||
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
|
||||
|
||||
`get_schema_fields(self, view)`
|
||||
|
||||
The method should return a list of `coreapi.Field` instances.
|
||||
*A custom pagination style, using the 'Link' header*
|
||||
|
||||
---
|
||||
|
||||
|
@ -312,7 +303,7 @@ The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagi
|
|||
|
||||
## link-header-pagination
|
||||
|
||||
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [Github's developer documentation](github-link-pagination).
|
||||
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [GitHub REST API documentation][github-traversing-with-pagination].
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
|
||||
[link-header]: ../img/link-header-pagination.png
|
||||
|
@ -322,3 +313,4 @@ The [`django-rest-framework-link-header-pagination` package][drf-link-header-pag
|
|||
[drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination
|
||||
[disqus-cursor-api]: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api
|
||||
[float_cursor_pagination_example]: https://gist.github.com/keturn/8bc88525a183fd41c73ffb729b8865be#file-fpcursorpagination-py
|
||||
[github-traversing-with-pagination]: https://docs.github.com/en/rest/guides/traversing-with-pagination
|
||||
|
|
|
@ -11,11 +11,11 @@ sending more complex data than simple forms
|
|||
>
|
||||
> — Malcom Tredinnick, [Django developers group][cite]
|
||||
|
||||
REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
|
||||
REST framework includes a number of built-in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
|
||||
|
||||
## How the parser is determined
|
||||
|
||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||
|
||||
---
|
||||
|
||||
|
@ -87,7 +87,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
|
|||
|
||||
## MultiPartParser
|
||||
|
||||
Parses multipart HTML form content, which supports file uploads. Both `request.data` will be populated with a `QueryDict`.
|
||||
Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
||||
|
|
|
@ -24,9 +24,9 @@ A slightly less strict style of permission would be to allow full access to auth
|
|||
Permissions in REST framework are always defined as a list of permission classes.
|
||||
|
||||
Before running the main body of the view each permission in the list is checked.
|
||||
If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
|
||||
If any permission check fails, an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
|
||||
|
||||
When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
|
||||
When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
|
||||
|
||||
* The request was successfully authenticated, but permission was denied. *— An HTTP 403 Forbidden response will be returned.*
|
||||
* The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *— An HTTP 403 Forbidden response will be returned.*
|
||||
|
@ -165,19 +165,19 @@ This permission is suitable if you want your API to only be accessible to a subs
|
|||
|
||||
## IsAuthenticatedOrReadOnly
|
||||
|
||||
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
|
||||
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthenticated users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
|
||||
|
||||
This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.
|
||||
|
||||
## DjangoModelPermissions
|
||||
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned.
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`.
|
||||
|
||||
* `POST` requests require the user to have the `add` permission on the model.
|
||||
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
|
||||
* `DELETE` requests require the user to have the `delete` permission on the model.
|
||||
|
||||
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||
The default behavior can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||
|
||||
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
||||
|
||||
|
@ -201,7 +201,7 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid
|
|||
|
||||
---
|
||||
|
||||
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian` package][django-rest-framework-guardian]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
|
||||
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian2` package][django-rest-framework-guardian2]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
|
||||
|
||||
---
|
||||
|
||||
|
@ -286,7 +286,7 @@ The following table lists the access restriction methods and the level of contro
|
|||
|
||||
| | `queryset` | `permission_classes` | `serializer_class` |
|
||||
|------------------------------------|------------|----------------------|--------------------|
|
||||
| Action: list | global | no | object-level* |
|
||||
| Action: list | global | global | object-level* |
|
||||
| Action: create | no | global | object-level |
|
||||
| Action: retrieve | global | object-level | object-level |
|
||||
| Action: update | global | object-level | object-level |
|
||||
|
@ -324,6 +324,10 @@ The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to
|
|||
|
||||
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
|
||||
|
||||
## Rest Framework Roles
|
||||
|
||||
The [Rest Framework Roles][rest-framework-roles] makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.
|
||||
|
||||
## Django REST Framework API Key
|
||||
|
||||
The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. _machines_) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
|
||||
|
@ -349,8 +353,9 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp
|
|||
[rest-condition]: https://github.com/caxap/rest_condition
|
||||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
|
||||
[rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles
|
||||
[djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/
|
||||
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
|
||||
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||
[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2
|
||||
[drf-access-policy]: https://github.com/rsinger86/drf-access-policy
|
||||
[drf-psq]: https://github.com/drf-psq/drf-psq
|
||||
|
|
|
@ -17,6 +17,37 @@ Relational fields are used to represent model relationships. They can be applie
|
|||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
**Note:** REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an orm relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
|
||||
|
||||
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.SlugRelatedField(
|
||||
many=True,
|
||||
read_only=True,
|
||||
slug_field='title'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
# For each album object, tracks should be fetched from database
|
||||
qs = Album.objects.all()
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
|
||||
If `AlbumSerializer` is used to serialize a fairly large queryset with `many=True` then it could be a serious performance problem. Optimizing the queryset passed to `AlbumSerializer` with:
|
||||
|
||||
qs = Album.objects.prefetch_related('tracks')
|
||||
# No additional database hits required
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
|
||||
would solve the issue.
|
||||
|
||||
---
|
||||
|
||||
#### Inspecting relationships.
|
||||
|
||||
When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.
|
||||
|
@ -215,7 +246,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
|
|||
|
||||
## HyperlinkedIdentityField
|
||||
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
||||
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
|
||||
|
@ -247,7 +278,7 @@ This field is always read-only.
|
|||
|
||||
As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_
|
||||
in the representation of the object that refers to it.
|
||||
Such nested relationships can be expressed by using serializers as fields.
|
||||
Such nested relationships can be expressed by using serializers as fields.
|
||||
|
||||
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
|
||||
|
||||
|
@ -463,8 +494,8 @@ This behavior is intended to prevent a template from being unable to render in a
|
|||
|
||||
There are two keyword arguments you can use to control this behavior:
|
||||
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
|
||||
|
||||
|
@ -597,12 +628,16 @@ The [drf-nested-routers package][drf-nested-routers] provides routers and relati
|
|||
|
||||
The [rest-framework-generic-relations][drf-nested-relations] library provides read/write serialization for generic foreign keys.
|
||||
|
||||
The [rest-framework-gm2m-relations][drf-gm2m-relations] library provides read/write serialization for [django-gm2m][django-gm2m-field].
|
||||
|
||||
[cite]: http://users.ece.utexas.edu/~adnan/pike.html
|
||||
[reverse-relationships]: https://docs.djangoproject.com/en/stable/topics/db/queries/#following-relationships-backward
|
||||
[routers]: https://www.django-rest-framework.org/api-guide/routers#defaultrouter
|
||||
[generic-relations]: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#id1
|
||||
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
|
||||
[drf-nested-relations]: https://github.com/Ian-Foote/rest-framework-generic-relations
|
||||
[drf-gm2m-relations]: https://github.com/mojtabaakbari221b/rest-framework-gm2m-relations
|
||||
[django-gm2m-field]: https://github.com/tkhyn/django-gm2m
|
||||
[django-intermediary-manytomany]: https://docs.djangoproject.com/en/stable/topics/db/models/#intermediary-manytomany
|
||||
[dealing-with-nested-objects]: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
|
||||
[to_internal_value]: https://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data
|
||||
|
|
|
@ -105,7 +105,7 @@ The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat
|
|||
|
||||
---
|
||||
|
||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionay and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
|
||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
|
||||
|
||||
```
|
||||
response.data = {'results': response.data}
|
||||
|
@ -192,7 +192,7 @@ By default the response content will be rendered with the highest priority rende
|
|||
def get_default_renderer(self, view):
|
||||
return JSONRenderer()
|
||||
|
||||
## AdminRenderer
|
||||
## AdminRenderer
|
||||
|
||||
Renders data into HTML for an admin-like display:
|
||||
|
||||
|
@ -257,7 +257,7 @@ This renderer is used for rendering HTML multipart form data. **It is not suita
|
|||
|
||||
# Custom renderers
|
||||
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method.
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, accepted_media_type=None, renderer_context=None)` method.
|
||||
|
||||
The method should return a bytestring, which will be used as the body of the HTTP response.
|
||||
|
||||
|
@ -267,7 +267,7 @@ The arguments passed to the `.render()` method are:
|
|||
|
||||
The request data, as set by the `Response()` instantiation.
|
||||
|
||||
### `media_type=None`
|
||||
### `accepted_media_type=None`
|
||||
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
|
||||
|
@ -283,7 +283,7 @@ By default this will include the following keys: `view`, `request`, `response`,
|
|||
|
||||
The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response.
|
||||
|
||||
from django.utils.encoding import smart_text
|
||||
from django.utils.encoding import smart_str
|
||||
from rest_framework import renderers
|
||||
|
||||
|
||||
|
@ -291,8 +291,8 @@ The following is an example plaintext renderer that will return a response with
|
|||
media_type = 'text/plain'
|
||||
format = 'txt'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
return smart_text(data, encoding=self.charset)
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return smart_str(data, encoding=self.charset)
|
||||
|
||||
## Setting the character set
|
||||
|
||||
|
@ -303,7 +303,7 @@ By default renderer classes are assumed to be using the `UTF-8` encoding. To us
|
|||
format = 'txt'
|
||||
charset = 'iso-8859-1'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data.encode(self.charset)
|
||||
|
||||
Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding.
|
||||
|
@ -318,7 +318,7 @@ In some cases you may also want to set the `render_style` attribute to `'binary'
|
|||
charset = None
|
||||
render_style = 'binary'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data
|
||||
|
||||
---
|
||||
|
@ -332,7 +332,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
|
|||
* Specify multiple types of HTML representation for API clients to use.
|
||||
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
|
||||
|
||||
## Varying behaviour by media type
|
||||
## Varying behavior by media type
|
||||
|
||||
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
|
||||
|
||||
|
@ -470,15 +470,15 @@ Modify your REST framework settings.
|
|||
|
||||
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
|
||||
|
||||
## XLSX (Binary Spreadsheet Endpoints)
|
||||
## Microsoft Excel: XLSX (Binary Spreadsheet Endpoints)
|
||||
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-renderer-xlsx][drf-renderer-xlsx], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-excel][drf-excel], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install drf-renderer-xlsx
|
||||
$ pip install drf-excel
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
|
@ -488,15 +488,15 @@ Modify your REST framework settings.
|
|||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
'drf_renderer_xlsx.renderers.XLSXRenderer',
|
||||
'drf_excel.renderers.XLSXRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example:
|
||||
|
||||
from rest_framework.viewsets import ReadOnlyModelViewSet
|
||||
from drf_renderer_xlsx.mixins import XLSXFileMixin
|
||||
from drf_renderer_xlsx.renderers import XLSXRenderer
|
||||
from drf_excel.mixins import XLSXFileMixin
|
||||
from drf_excel.renderers import XLSXRenderer
|
||||
|
||||
from .models import MyExampleModel
|
||||
from .serializers import MyExampleSerializer
|
||||
|
@ -525,10 +525,10 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
|
||||
## LaTeX
|
||||
|
||||
[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble].
|
||||
[Rest Framework Latex] provides a renderer that outputs PDFs using Lualatex. It is maintained by [Pebble (S/F Software)][mypebble].
|
||||
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/stable/template-response/#the-rendering-process
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/#the-rendering-process
|
||||
[conneg]: content-negotiation.md
|
||||
[html-and-forms]: ../topics/html-and-forms.md
|
||||
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
|
||||
|
@ -549,7 +549,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[mjumbewu]: https://github.com/mjumbewu
|
||||
[flipperpa]: https://github.com/flipperpa
|
||||
[wharton]: https://github.com/wharton
|
||||
[drf-renderer-xlsx]: https://github.com/wharton/drf-renderer-xlsx
|
||||
[drf-excel]: https://github.com/wharton/drf-excel
|
||||
[vbabiy]: https://github.com/vbabiy
|
||||
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
||||
|
|
|
@ -49,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
|
|||
|
||||
# Content negotiation
|
||||
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types.
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
|
||||
|
||||
## .accepted_renderer
|
||||
|
||||
|
|
|
@ -32,16 +32,16 @@ You should **include the request as a keyword argument** to the function, for ex
|
|||
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.views import APIView
|
||||
from django.utils.timezone import now
|
||||
from django.utils.timezone import now
|
||||
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
}
|
||||
return Response(data)
|
||||
return Response(data)
|
||||
|
||||
## reverse_lazy
|
||||
|
||||
|
@ -54,5 +54,5 @@ As with the `reverse` function, you should **include the request as a keyword ar
|
|||
api_root = reverse_lazy('api-root', request=request)
|
||||
|
||||
[cite]: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
|
||||
[reverse]: https://docs.djangoproject.com/en/stable/topics/http/urls/#reverse
|
||||
[reverse-lazy]: https://docs.djangoproject.com/en/stable/topics/http/urls/#reverse-lazy
|
||||
[reverse]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse
|
||||
[reverse-lazy]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy
|
||||
|
|
|
@ -142,6 +142,24 @@ The above example would now generate the following URL pattern:
|
|||
* URL path: `^users/{pk}/change-password/$`
|
||||
* URL name: `'user-change_password'`
|
||||
|
||||
### Using Django `path()` with routers
|
||||
|
||||
By default, the URLs created by routers use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router, in this case [path converters][path-converters-topic-reference] are used. For example:
|
||||
|
||||
router = SimpleRouter(use_regex_path=False)
|
||||
|
||||
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset or `lookup_value_converter` if using path converters. For example, you can limit the lookup to valid UUIDs:
|
||||
|
||||
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
lookup_field = 'my_model_id'
|
||||
lookup_value_regex = '[0-9a-f]{32}'
|
||||
|
||||
class MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
lookup_field = 'my_model_uuid'
|
||||
lookup_value_converter = 'uuid'
|
||||
|
||||
Note that path converters will be used on all URLs registered in the router, including viewset actions.
|
||||
|
||||
# API Guide
|
||||
|
||||
## SimpleRouter
|
||||
|
@ -160,19 +178,13 @@ This router includes routes for the standard set of `list`, `create`, `retrieve`
|
|||
<tr><td>{prefix}/{lookup}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
|
||||
</table>
|
||||
|
||||
By default the URLs created by `SimpleRouter` are appended with a trailing slash.
|
||||
By default, the URLs created by `SimpleRouter` are appended with a trailing slash.
|
||||
This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example:
|
||||
|
||||
router = SimpleRouter(trailing_slash=False)
|
||||
|
||||
Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.
|
||||
|
||||
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs:
|
||||
|
||||
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
lookup_field = 'my_model_id'
|
||||
lookup_value_regex = '[0-9a-f]{32}'
|
||||
|
||||
## DefaultRouter
|
||||
|
||||
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
|
||||
|
@ -338,5 +350,6 @@ The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions
|
|||
[drf-extensions-nested-viewsets]: https://chibisov.github.io/drf-extensions/docs/#nested-routes
|
||||
[drf-extensions-collection-level-controllers]: https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
|
||||
[drf-extensions-customizable-endpoint-names]: https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
|
||||
[url-namespace-docs]: https://docs.djangoproject.com/en/1.11/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/2.0/ref/urls/#include
|
||||
[url-namespace-docs]: https://docs.djangoproject.com/en/4.0/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/4.0/ref/urls/#include
|
||||
[path-converters-topic-reference]: https://docs.djangoproject.com/en/2.0/topics/http/urls/#path-converters
|
||||
|
|
|
@ -9,6 +9,23 @@ source:
|
|||
>
|
||||
> — Heroku, [JSON Schema for the Heroku Platform API][cite]
|
||||
|
||||
---
|
||||
|
||||
**Deprecation notice:**
|
||||
|
||||
REST framework's built-in support for generating OpenAPI schemas is
|
||||
**deprecated** in favor of 3rd party packages that can provide this
|
||||
functionality instead. The built-in support will be moved into a separate
|
||||
package and then subsequently retired over the next releases.
|
||||
|
||||
As a full-fledged replacement, we recommend the [drf-spectacular] package.
|
||||
It has extensive support for generating OpenAPI 3 schemas from
|
||||
REST framework APIs, with both automatic and customisable options available.
|
||||
For further information please refer to
|
||||
[Documenting your API](../topics/documenting-your-api.md#drf-spectacular).
|
||||
|
||||
---
|
||||
|
||||
API schemas are a useful tool that allow for a range of use cases, including
|
||||
generating reference documentation, or driving dynamic client libraries that
|
||||
can interact with your API.
|
||||
|
@ -39,10 +56,11 @@ The following sections explain more.
|
|||
|
||||
### Install dependencies
|
||||
|
||||
pip install pyyaml uritemplate
|
||||
pip install pyyaml uritemplate inflection
|
||||
|
||||
* `pyyaml` is used to generate schema into YAML-based OpenAPI format.
|
||||
* `uritemplate` is used internally to get parameters in path.
|
||||
* `inflection` is used to pluralize operations more appropriately in the list endpoints.
|
||||
|
||||
### Generating a static schema with the `generateschema` management command
|
||||
|
||||
|
@ -77,11 +95,13 @@ urlpatterns = [
|
|||
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
|
||||
# * `title` and `description` parameters are passed to `SchemaGenerator`.
|
||||
# * Provide view name for use with `reverse()`.
|
||||
path('openapi', get_schema_view(
|
||||
title="Your Project",
|
||||
description="API for all things …",
|
||||
version="1.0.0"
|
||||
), name='openapi-schema'),
|
||||
path(
|
||||
"openapi",
|
||||
get_schema_view(
|
||||
title="Your Project", description="API for all things …", version="1.0.0"
|
||||
),
|
||||
name="openapi-schema",
|
||||
),
|
||||
# ...
|
||||
]
|
||||
```
|
||||
|
@ -122,6 +142,7 @@ The `get_schema_view()` helper takes the following keyword arguments:
|
|||
url='https://www.example.org/api/',
|
||||
patterns=schema_url_patterns,
|
||||
)
|
||||
* `public`: May be used to specify if schema should bypass views permissions. Default to False
|
||||
|
||||
* `generator_class`: May be used to specify a `SchemaGenerator` subclass to be
|
||||
passed to the `SchemaView`.
|
||||
|
@ -165,7 +186,7 @@ In order to customize the top-level schema, subclass
|
|||
as an argument to the `generateschema` command or `get_schema_view()` helper
|
||||
function.
|
||||
|
||||
### get_schema(self, request)
|
||||
### get_schema(self, request=None, public=False)
|
||||
|
||||
Returns a dictionary that represents the OpenAPI schema:
|
||||
|
||||
|
@ -241,11 +262,13 @@ class CustomSchema(AutoSchema):
|
|||
"""
|
||||
AutoSchema subclass using schema_extra_info on the view.
|
||||
"""
|
||||
|
||||
...
|
||||
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = CustomSchema()
|
||||
schema_extra_info = ... some extra info ...
|
||||
schema_extra_info = ... # some extra info
|
||||
```
|
||||
|
||||
Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the
|
||||
|
@ -260,10 +283,13 @@ class BaseSchema(AutoSchema):
|
|||
"""
|
||||
AutoSchema subclass that knows how to use extra_info.
|
||||
"""
|
||||
|
||||
...
|
||||
|
||||
|
||||
class CustomSchema(BaseSchema):
|
||||
extra_info = ... some extra info ...
|
||||
extra_info = ... # some extra info
|
||||
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = CustomSchema()
|
||||
|
@ -284,15 +310,14 @@ class CustomSchema(BaseSchema):
|
|||
self.extra_info = kwargs.pop("extra_info")
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = CustomSchema(
|
||||
extra_info=... some extra info ...
|
||||
)
|
||||
schema = CustomSchema(extra_info=...) # some extra info
|
||||
```
|
||||
|
||||
This saves you having to create a custom subclass per-view for a commonly used option.
|
||||
|
||||
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
|
||||
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
|
||||
the more commonly needed options do.
|
||||
|
||||
### `AutoSchema` methods
|
||||
|
@ -300,7 +325,7 @@ the more commonly needed options do.
|
|||
#### `get_components()`
|
||||
|
||||
Generates the OpenAPI components that describe request and response bodies,
|
||||
deriving their properties from the serializer.
|
||||
deriving their properties from the serializer.
|
||||
|
||||
Returns a dictionary mapping the component name to the generated
|
||||
representation. By default this has just a single pair but you may override
|
||||
|
@ -313,6 +338,11 @@ Computes the component's name from the serializer.
|
|||
|
||||
You may see warnings if your API has duplicate component names. If so you can override `get_component_name()` or pass the `component_name` `__init__()` kwarg (see below) to provide different names.
|
||||
|
||||
#### `get_reference()`
|
||||
|
||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||
|
||||
|
||||
#### `map_serializer()`
|
||||
|
||||
Maps serializers to their OpenAPI representations.
|
||||
|
@ -375,6 +405,20 @@ operationIds.
|
|||
In order to work around this, you can override `get_operation_id_base()` to
|
||||
provide a different base for name part of the ID.
|
||||
|
||||
#### `get_serializer()`
|
||||
|
||||
If the view has implemented `get_serializer()`, returns the result.
|
||||
|
||||
#### `get_request_serializer()`
|
||||
|
||||
By default returns `get_serializer()` but can be overridden to
|
||||
differentiate between request and response objects.
|
||||
|
||||
#### `get_response_serializer()`
|
||||
|
||||
By default returns `get_serializer()` but can be overridden to
|
||||
differentiate between request and response objects.
|
||||
|
||||
### `AutoSchema.__init__()` kwargs
|
||||
|
||||
`AutoSchema` provides a number of `__init__()` kwargs that can be used for
|
||||
|
@ -407,6 +451,7 @@ If your views have related customizations that are needed frequently, you can
|
|||
create a base `AutoSchema` subclass for your project that takes additional
|
||||
`__init__()` kwargs to save subclassing `AutoSchema` for each view.
|
||||
|
||||
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
|
||||
[openapi]: https://github.com/OAI/OpenAPI-Specification
|
||||
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
|
||||
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject
|
||||
|
@ -417,3 +462,4 @@ create a base `AutoSchema` subclass for your project that takes additional
|
|||
[openapi-generator]: https://github.com/OpenAPITools/openapi-generator
|
||||
[swagger-codegen]: https://github.com/swagger-api/swagger-codegen
|
||||
[info-object]: https://swagger.io/specification/#infoObject
|
||||
[drf-spectacular]: https://drf-spectacular.readthedocs.io/en/latest/readme.html
|
||||
|
|
|
@ -116,7 +116,7 @@ Calling `.save()` will either create a new instance, or update an existing insta
|
|||
# .save() will update the existing `comment` instance.
|
||||
serializer = CommentSerializer(comment, data=data)
|
||||
|
||||
Both the `.create()` and `.update()` methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.
|
||||
Both the `.create()` and `.update()` methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class.
|
||||
|
||||
#### Passing additional attributes to `.save()`
|
||||
|
||||
|
@ -226,14 +226,14 @@ Individual fields on a serializer can include validators, by declaring them on t
|
|||
raise serializers.ValidationError('Not a multiple of ten')
|
||||
|
||||
class GameRecord(serializers.Serializer):
|
||||
score = IntegerField(validators=[multiple_of_ten])
|
||||
score = serializers.IntegerField(validators=[multiple_of_ten])
|
||||
...
|
||||
|
||||
Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner `Meta` class, like so:
|
||||
|
||||
class EventSerializer(serializers.Serializer):
|
||||
name = serializers.CharField()
|
||||
room_number = serializers.IntegerField(choices=[101, 102, 103, 201])
|
||||
room_number = serializers.ChoiceField(choices=[101, 102, 103, 201])
|
||||
date = serializers.DateField()
|
||||
|
||||
class Meta:
|
||||
|
@ -524,6 +524,7 @@ You can add extra fields to a `ModelSerializer` or override the default fields b
|
|||
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ['url', 'groups']
|
||||
|
||||
Extra fields can correspond to any property or callable on the model.
|
||||
|
||||
|
@ -593,15 +594,15 @@ The ModelSerializer class also exposes an API that you can override in order to
|
|||
|
||||
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
|
||||
|
||||
### `.serializer_field_mapping`
|
||||
### `serializer_field_mapping`
|
||||
|
||||
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
|
||||
|
||||
### `.serializer_related_field`
|
||||
### `serializer_related_field`
|
||||
|
||||
This property should be the serializer field class, that is used for relational fields by default.
|
||||
|
||||
For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`.
|
||||
For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
|
||||
|
||||
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
|
||||
|
||||
|
@ -621,13 +622,13 @@ Defaults to `serializers.ChoiceField`
|
|||
|
||||
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
|
||||
|
||||
### `.build_standard_field(self, field_name, model_field)`
|
||||
### `build_standard_field(self, field_name, model_field)`
|
||||
|
||||
Called to generate a serializer field that maps to a standard model field.
|
||||
|
||||
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
|
||||
|
||||
### `.build_relational_field(self, field_name, relation_info)`
|
||||
### `build_relational_field(self, field_name, relation_info)`
|
||||
|
||||
Called to generate a serializer field that maps to a relational model field.
|
||||
|
||||
|
@ -635,7 +636,7 @@ The default implementation returns a serializer class based on the `serializer_r
|
|||
|
||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||
|
||||
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||
### `build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||
|
||||
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
|
||||
|
||||
|
@ -645,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one.
|
|||
|
||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||
|
||||
### `.build_property_field(self, field_name, model_class)`
|
||||
### `build_property_field(self, field_name, model_class)`
|
||||
|
||||
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
|
||||
|
||||
The default implementation returns a `ReadOnlyField` class.
|
||||
|
||||
### `.build_url_field(self, field_name, model_class)`
|
||||
### `build_url_field(self, field_name, model_class)`
|
||||
|
||||
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
|
||||
|
||||
### `.build_unknown_field(self, field_name, model_class)`
|
||||
### `build_unknown_field(self, field_name, model_class)`
|
||||
|
||||
Called when the field name did not map to any model field or model property.
|
||||
The default implementation raises an error, although subclasses may customize this behavior.
|
||||
|
@ -755,6 +756,14 @@ The following argument can also be passed to a `ListSerializer` field or a seria
|
|||
|
||||
This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
|
||||
### `max_length`
|
||||
|
||||
This is `None` by default, but can be set to a positive integer if you want to validate that the list contains no more than this number of elements.
|
||||
|
||||
### `min_length`
|
||||
|
||||
This is `None` by default, but can be set to a positive integer if you want to validate that the list contains no fewer than this number of elements.
|
||||
|
||||
### Customizing `ListSerializer` behavior
|
||||
|
||||
There *are* a few use cases when you might want to customize the `ListSerializer` behavior. For example:
|
||||
|
@ -836,8 +845,6 @@ Here's an example of how you might choose to implement multiple updates:
|
|||
class Meta:
|
||||
list_serializer_class = BookListSerializer
|
||||
|
||||
It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the `allow_add_remove` behavior that was present in REST framework 2.
|
||||
|
||||
#### Customizing ListSerializer initialization
|
||||
|
||||
When a serializer with `many=True` is instantiated, we need to determine which arguments and keyword arguments should be passed to the `.__init__()` method for both the child `Serializer` class, and for the parent `ListSerializer` class.
|
||||
|
@ -877,7 +884,7 @@ Because this class provides the same interface as the `Serializer` class, you ca
|
|||
|
||||
The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.
|
||||
|
||||
##### Read-only `BaseSerializer` classes
|
||||
#### Read-only `BaseSerializer` classes
|
||||
|
||||
To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model:
|
||||
|
||||
|
@ -901,7 +908,7 @@ We can now use this class to serialize single `HighScore` instances:
|
|||
def high_score(request, pk):
|
||||
instance = HighScore.objects.get(pk=pk)
|
||||
serializer = HighScoreSerializer(instance)
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
Or use it to serialize multiple instances:
|
||||
|
||||
|
@ -909,9 +916,9 @@ Or use it to serialize multiple instances:
|
|||
def all_high_scores(request):
|
||||
queryset = HighScore.objects.order_by('-score')
|
||||
serializer = HighScoreSerializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
##### Read-write `BaseSerializer` classes
|
||||
#### Read-write `BaseSerializer` classes
|
||||
|
||||
To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format.
|
||||
|
||||
|
@ -940,8 +947,8 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
'player_name': 'May not be more than 10 characters.'
|
||||
})
|
||||
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
return {
|
||||
'score': int(score),
|
||||
'player_name': player_name
|
||||
|
@ -960,7 +967,7 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
|
||||
The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
|
||||
|
||||
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
|
||||
The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations.
|
||||
|
||||
class ObjectSerializer(serializers.BaseSerializer):
|
||||
"""
|
||||
|
@ -1012,7 +1019,7 @@ Some reasons this might be useful include...
|
|||
|
||||
The signatures for these methods are as follows:
|
||||
|
||||
#### `.to_representation(self, instance)`
|
||||
#### `to_representation(self, instance)`
|
||||
|
||||
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
|
||||
|
||||
|
@ -1024,7 +1031,7 @@ May be overridden in order to modify the representation style. For example:
|
|||
ret['username'] = ret['username'].lower()
|
||||
return ret
|
||||
|
||||
#### ``.to_internal_value(self, data)``
|
||||
#### ``to_internal_value(self, data)``
|
||||
|
||||
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
||||
|
||||
|
@ -1087,7 +1094,7 @@ For example, if you wanted to be able to set which fields should be used by a se
|
|||
fields = kwargs.pop('fields', None)
|
||||
|
||||
# Instantiate the superclass normally
|
||||
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if fields is not None:
|
||||
# Drop any fields that are not specified in the `fields` argument.
|
||||
|
@ -1180,7 +1187,7 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
|
|||
|
||||
## DRF Encrypt Content
|
||||
|
||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
||||
|
|
|
@ -163,6 +163,12 @@ The string that should used for any versioning parameters, such as in the media
|
|||
|
||||
Default: `'version'`
|
||||
|
||||
#### DEFAULT_VERSIONING_CLASS
|
||||
|
||||
The default versioning scheme to use.
|
||||
|
||||
Default: `None`
|
||||
|
||||
---
|
||||
|
||||
## Authentication settings
|
||||
|
@ -454,4 +460,4 @@ Default: `None`
|
|||
[cite]: https://www.python.org/dev/peps/pep-0020/
|
||||
[rfc4627]: https://www.ietf.org/rfc/rfc4627.txt
|
||||
[heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses
|
||||
[strftime]: https://docs.python.org/3/library/time.html#time.strftime
|
||||
[strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
|
||||
|
|
|
@ -41,6 +41,8 @@ This class of status code indicates a provisional response. There are no 1xx st
|
|||
|
||||
HTTP_100_CONTINUE
|
||||
HTTP_101_SWITCHING_PROTOCOLS
|
||||
HTTP_102_PROCESSING
|
||||
HTTP_103_EARLY_HINTS
|
||||
|
||||
## Successful - 2xx
|
||||
|
||||
|
@ -93,9 +95,11 @@ The 4xx class of status code is intended for cases in which the client seems to
|
|||
HTTP_415_UNSUPPORTED_MEDIA_TYPE
|
||||
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
|
||||
HTTP_417_EXPECTATION_FAILED
|
||||
HTTP_421_MISDIRECTED_REQUEST
|
||||
HTTP_422_UNPROCESSABLE_ENTITY
|
||||
HTTP_423_LOCKED
|
||||
HTTP_424_FAILED_DEPENDENCY
|
||||
HTTP_425_TOO_EARLY
|
||||
HTTP_426_UPGRADE_REQUIRED
|
||||
HTTP_428_PRECONDITION_REQUIRED
|
||||
HTTP_429_TOO_MANY_REQUESTS
|
||||
|
|
|
@ -25,9 +25,12 @@ The `APIRequestFactory` class supports an almost identical API to Django's stand
|
|||
factory = APIRequestFactory()
|
||||
request = factory.post('/notes/', {'title': 'new idea'})
|
||||
|
||||
# Using the standard RequestFactory API to encode JSON data
|
||||
request = factory.post('/notes/', {'title': 'new idea'}, content_type='application/json')
|
||||
|
||||
#### Using the `format` argument
|
||||
|
||||
Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a content type other than multipart form data. For example:
|
||||
Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a wide set of request formats. When using this argument, the factory will select an appropriate renderer and its configured `content_type`. For example:
|
||||
|
||||
# Create a JSON POST request
|
||||
factory = APIRequestFactory()
|
||||
|
@ -41,7 +44,7 @@ To support a wider set of request formats, or change the default format, [see th
|
|||
|
||||
If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example:
|
||||
|
||||
request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
|
||||
request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml')
|
||||
|
||||
#### PUT and PATCH with form data
|
||||
|
||||
|
@ -234,7 +237,7 @@ If you're using `SessionAuthentication` then you'll need to include a CSRF token
|
|||
for any `POST`, `PUT`, `PATCH` or `DELETE` requests.
|
||||
|
||||
You can do so by following the same flow that a JavaScript based client would use.
|
||||
First make a `GET` request in order to obtain a CRSF token, then present that
|
||||
First, make a `GET` request in order to obtain a CSRF token, then present that
|
||||
token in the following request.
|
||||
|
||||
For example...
|
||||
|
@ -259,7 +262,7 @@ With careful usage both the `RequestsClient` and the `CoreAPIClient` provide
|
|||
the ability to write test cases that can run either in development, or be run
|
||||
directly against your staging server or production environment.
|
||||
|
||||
Using this style to create basic tests of a few core piece of functionality is
|
||||
Using this style to create basic tests of a few core pieces of functionality is
|
||||
a powerful way to validate your live service. Doing so may require some careful
|
||||
attention to setup and teardown to ensure that the tests run in a way that they
|
||||
do not directly affect customer data.
|
||||
|
@ -299,7 +302,7 @@ similar way as with `RequestsClient`.
|
|||
|
||||
# API Test cases
|
||||
|
||||
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`.
|
||||
REST framework includes the following test case classes, that mirror the existing [Django's test case classes][provided_test_case_classes], but use `APIClient` instead of Django's default `Client`.
|
||||
|
||||
* `APISimpleTestCase`
|
||||
* `APITransactionTestCase`
|
||||
|
@ -413,5 +416,6 @@ For example, to add support for using `format='html'` in test requests, you migh
|
|||
[client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
|
||||
[requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory
|
||||
[configuration]: #configuration
|
||||
[refresh_from_db_docs]: https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.refresh_from_db
|
||||
[refresh_from_db_docs]: https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.refresh_from_db
|
||||
[session_objects]: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
|
||||
[provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes
|
||||
|
|
|
@ -19,6 +19,10 @@ Multiple throttles can also be used if you want to impose both burst throttling
|
|||
|
||||
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
|
||||
|
||||
**The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
|
||||
|
||||
The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
|
||||
|
||||
## How throttling is determined
|
||||
|
||||
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
|
||||
|
@ -41,14 +45,14 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
|
|||
}
|
||||
}
|
||||
|
||||
The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
|
||||
The rates used in `DEFAULT_THROTTLE_RATES` can be specified over a period of second, minute, hour or day. The period must be specified after the `/` separator using `s`, `m`, `h` or `d`, respectively. For increased clarity, extended units such as `second`, `minute`, `hour`, `day` or even abbreviations like `sec`, `min`, `hr` are allowed, as only the first character is relevant to identify the rate.
|
||||
|
||||
You can also set the throttling policy on a per-view or per-viewset basis,
|
||||
using the `APIView` class-based views.
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.throttling import UserRateThrottle
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleView(APIView):
|
||||
throttle_classes = [UserRateThrottle]
|
||||
|
@ -79,7 +83,7 @@ Throttle classes set in this way will override any viewset level class settings.
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
## How clients are identified
|
||||
## How clients are identified
|
||||
|
||||
The `X-Forwarded-For` HTTP header and `REMOTE_ADDR` WSGI variable are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `REMOTE_ADDR` variable from the WSGI environment will be used.
|
||||
|
||||
|
@ -102,6 +106,12 @@ If you need to use a cache other than `'default'`, you can do so by creating a c
|
|||
|
||||
You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute.
|
||||
|
||||
## A note on concurrency
|
||||
|
||||
The built-in throttle implementations are open to [race conditions][race], so under high concurrency they may allow a few extra requests through.
|
||||
|
||||
If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
@ -210,3 +220,4 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
|
|||
[identifying-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
|
||||
[cache-setting]: https://docs.djangoproject.com/en/stable/ref/settings/#caches
|
||||
[cache-docs]: https://docs.djangoproject.com/en/stable/topics/cache/#setting-up-the-cache
|
||||
[race]: https://en.wikipedia.org/wiki/Race_condition#Data_race
|
||||
|
|
|
@ -20,7 +20,7 @@ Validation in Django REST framework serializers is handled a little differently
|
|||
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
|
||||
|
||||
* It introduces a proper separation of concerns, making your code behavior more obvious.
|
||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
|
||||
|
||||
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
|
||||
|
@ -48,12 +48,12 @@ If we open up the Django shell using `manage.py shell` we can now
|
|||
CustomerReportSerializer():
|
||||
id = IntegerField(label='ID', read_only=True)
|
||||
time_raised = DateTimeField(read_only=True)
|
||||
reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>])
|
||||
reference = CharField(max_length=20, validators=[UniqueValidator(queryset=CustomerReportRecord.objects.all())])
|
||||
description = CharField(style={'type': 'textarea'})
|
||||
|
||||
The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
|
||||
|
||||
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.
|
||||
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. REST framework validators, like their Django counterparts, implement the `__eq__` method, allowing you to compare instances for equality.
|
||||
|
||||
---
|
||||
|
||||
|
@ -164,14 +164,18 @@ If you want the date field to be entirely hidden from the user, then use `Hidden
|
|||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
|
||||
|
||||
---
|
||||
|
||||
# Advanced field defaults
|
||||
|
||||
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator.
|
||||
For this purposes use `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation.
|
||||
|
||||
Two patterns that you may want to use for this sort of validation include:
|
||||
|
||||
* Using `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation.
|
||||
* Using a standard field with `read_only=True`, but that also includes a `default=…` argument. This field *will* be used in the serializer output representation, but cannot be set directly by the user.
|
||||
**Note:** Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behaviour-of-read_only-plus-default-on-field).
|
||||
|
||||
REST framework includes a couple of defaults that may be useful in this context.
|
||||
|
||||
|
@ -183,7 +187,7 @@ A default class that can be used to represent the current user. In order to use
|
|||
default=serializers.CurrentUserDefault()
|
||||
)
|
||||
|
||||
#### CreateOnlyDefault
|
||||
#### CreateOnlyDefault
|
||||
|
||||
A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted.
|
||||
|
||||
|
@ -208,7 +212,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute.
|
|||
|
||||
By default "unique together" validation enforces that all fields be
|
||||
`required=True`. In some cases, you might want to explicit apply
|
||||
`required=False` to one of the fields, in which case the desired behaviour
|
||||
`required=False` to one of the fields, in which case the desired behavior
|
||||
of the validation is ambiguous.
|
||||
|
||||
In this case you will typically need to exclude the validator from the
|
||||
|
@ -238,7 +242,7 @@ In the case of update operations on *nested* serializers there's no way of
|
|||
applying this exclusion, because the instance is not available.
|
||||
|
||||
Again, you'll probably want to explicitly remove the validator from the
|
||||
serializer class, and write the code the for the validation constraint
|
||||
serializer class, and write the code for the validation constraint
|
||||
explicitly, in a `.validate()` method, or in the view.
|
||||
|
||||
## Debugging complex cases
|
||||
|
@ -295,13 +299,14 @@ To write a class-based validator, use the `__call__` method. Class-based validat
|
|||
|
||||
In some advanced cases you might want a validator to be passed the serializer
|
||||
field it is being used with as additional context. You can do so by setting
|
||||
a `requires_context = True` attribute on the validator. The `__call__` method
|
||||
a `requires_context = True` attribute on the validator class. The `__call__` method
|
||||
will then be called with the `serializer_field`
|
||||
or `serializer` as an additional argument.
|
||||
|
||||
requires_context = True
|
||||
class MultipleOf:
|
||||
requires_context = True
|
||||
|
||||
def __call__(self, value, serializer_field):
|
||||
...
|
||||
def __call__(self, value, serializer_field):
|
||||
...
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/validators/
|
||||
|
|
|
@ -145,6 +145,7 @@ REST framework also allows you to work with regular function based views. It pr
|
|||
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
|
||||
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
|
||||
@api_view()
|
||||
def hello_world(request):
|
||||
|
@ -152,7 +153,7 @@ The core of this functionality is the `api_view` decorator, which takes a list o
|
|||
|
||||
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
|
||||
|
||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:
|
||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
|
||||
|
||||
@api_view(['GET', 'POST'])
|
||||
def hello_world(request):
|
||||
|
|
|
@ -116,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`.
|
|||
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
|
||||
* `description` - the display description for the individual view of a viewset.
|
||||
|
||||
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||
You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||
|
||||
def get_permissions(self):
|
||||
"""
|
||||
|
@ -125,9 +125,11 @@ You may inspect these attributes to adjust behaviour based on the current action
|
|||
if self.action == 'list':
|
||||
permission_classes = [IsAuthenticated]
|
||||
else:
|
||||
permission_classes = [IsAdmin]
|
||||
permission_classes = [IsAdminUser]
|
||||
return [permission() for permission in permission_classes]
|
||||
|
||||
**Note**: the `action` attribute is not available in the `get_parsers`, `get_authenticators` and `get_content_negotiator` methods, as it is set _after_ they are called in the framework lifecycle. If you override one of these methods and try to access the `action` attribute in them, you will get an `AttributeError` error.
|
||||
|
||||
## Marking extra actions for routing
|
||||
|
||||
If you have ad-hoc methods that should be routable, you can mark them as such with the `@action` decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the `detail` argument to `True` or `False`. The router will configure its URL patterns accordingly. e.g., the `DefaultRouter` will configure detail actions to contain `pk` in their URL patterns.
|
||||
|
@ -178,6 +180,13 @@ The `action` decorator will route `GET` requests by default, but may also accept
|
|||
def unset_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
Argument `methods` also supports HTTP methods defined as [HTTPMethod](https://docs.python.org/3/library/http.html#http.HTTPMethod). Example below is identical to the one above:
|
||||
|
||||
from http import HTTPMethod
|
||||
|
||||
@action(detail=True, methods=[HTTPMethod.POST, HTTPMethod.DELETE])
|
||||
def unset_password(self, request, pk=None):
|
||||
...
|
||||
|
||||
The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...:
|
||||
|
||||
|
@ -194,15 +203,16 @@ To view all extra actions, call the `.get_extra_actions()` method.
|
|||
Extra actions can map additional HTTP methods to separate `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.
|
||||
|
||||
```python
|
||||
@action(detail=True, methods=['put'], name='Change Password')
|
||||
def password(self, request, pk=None):
|
||||
"""Update the user's password."""
|
||||
...
|
||||
@action(detail=True, methods=["put"], name="Change Password")
|
||||
def password(self, request, pk=None):
|
||||
"""Update the user's password."""
|
||||
...
|
||||
|
||||
@password.mapping.delete
|
||||
def delete_password(self, request, pk=None):
|
||||
"""Delete the user's password."""
|
||||
...
|
||||
|
||||
@password.mapping.delete
|
||||
def delete_password(self, request, pk=None):
|
||||
"""Delete the user's password."""
|
||||
...
|
||||
```
|
||||
|
||||
## Reversing action URLs
|
||||
|
@ -213,14 +223,14 @@ Note that the `basename` is provided by the router during `ViewSet` registration
|
|||
|
||||
Using the example from the previous section:
|
||||
|
||||
```python
|
||||
>>> view.reverse_action('set-password', args=['1'])
|
||||
```pycon
|
||||
>>> view.reverse_action("set-password", args=["1"])
|
||||
'http://localhost:8000/api/users/1/set_password'
|
||||
```
|
||||
|
||||
Alternatively, you can use the `url_name` attribute set by the `@action` decorator.
|
||||
|
||||
```python
|
||||
```pycon
|
||||
>>> view.reverse_action(view.set_password.url_name, args=['1'])
|
||||
'http://localhost:8000/api/users/1/set_password'
|
||||
```
|
||||
|
@ -247,7 +257,7 @@ In order to use a `GenericViewSet` class you'll override the class and either mi
|
|||
|
||||
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
|
||||
|
||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||
|
||||
#### Example
|
||||
|
||||
|
@ -303,7 +313,7 @@ You may need to provide custom `ViewSet` classes that do not have the full set o
|
|||
|
||||
To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions:
|
||||
|
||||
from rest_framework import mixins
|
||||
from rest_framework import mixins, viewsets
|
||||
|
||||
class CreateListRetrieveViewSet(mixins.CreateModelMixin,
|
||||
mixins.ListModelMixin,
|
||||
|
|
|
@ -24,7 +24,7 @@ Notable features of this new release include:
|
|||
* Support for overriding how validation errors are handled by your API.
|
||||
* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
|
||||
* A more compact JSON output with unicode style encoding turned on by default.
|
||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||
|
||||
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
|
||||
|
||||
|
@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
|
|||
|
||||
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
||||
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
"""A custom read-only field that returns the class name."""
|
||||
|
|
|
@ -41,8 +41,8 @@ update your REST framework settings to include `DEFAULT_SCHEMA_CLASS` explicitly
|
|||
|
||||
```python
|
||||
REST_FRAMEWORK = {
|
||||
...
|
||||
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
|
||||
...: ...,
|
||||
"DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema",
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -74,10 +74,11 @@ urlpatterns = [
|
|||
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
|
||||
# * `title` and `description` parameters are passed to `SchemaGenerator`.
|
||||
# * Provide view name for use with `reverse()`.
|
||||
path('openapi', get_schema_view(
|
||||
title="Your Project",
|
||||
description="API for all things …"
|
||||
), name='openapi-schema'),
|
||||
path(
|
||||
"openapi",
|
||||
get_schema_view(title="Your Project", description="API for all things …"),
|
||||
name="openapi-schema",
|
||||
),
|
||||
# ...
|
||||
]
|
||||
```
|
||||
|
@ -142,6 +143,6 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), and [Lights On Software](https://lightsonsoftware.com).*
|
||||
|
||||
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/master/docs/coreapi/index.md
|
||||
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/3.14.0/docs/coreapi/index.md
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
||||
|
|
|
@ -43,10 +43,11 @@ be extracted from the class docstring:
|
|||
|
||||
```python
|
||||
class DocStringExampleListView(APIView):
|
||||
"""
|
||||
get: A description of my GET operation.
|
||||
post: A description of my POST operation.
|
||||
"""
|
||||
"""
|
||||
get: A description of my GET operation.
|
||||
post: A description of my POST operation.
|
||||
"""
|
||||
|
||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
|
@ -63,7 +64,7 @@ In some circumstances a Validator class or a Default class may need to access th
|
|||
* Uniqueness validators need to be able to determine the name of the field to which they are applied, in order to run an appropriate database query.
|
||||
* The `CurrentUserDefault` needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance.
|
||||
|
||||
Previous our approach to this was that implementations could include a `set_context` method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.
|
||||
Our previous approach to this was that implementations could include a `set_context` method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13.
|
||||
|
||||
Instead, validators or defaults which require the serializer context, should include a `requires_context = True` attribute on the class.
|
||||
|
||||
|
|
|
@ -30,18 +30,18 @@ in the URL path.
|
|||
|
||||
For example...
|
||||
|
||||
Method | Path | Tags
|
||||
Method | Path | Tags
|
||||
--------------------------------|-----------------|-------------
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||
`GET`, `POST` | `/users/` | `['users']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||
`GET`, `POST` | `/orders/` | `['orders']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||
`GET`, `POST` | `/users/` | `['users']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||
`GET`, `POST` | `/orders/` | `['orders']`
|
||||
|
||||
The tags used for a particular view may also be overridden...
|
||||
|
||||
```python
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(tags=['users', 'orders'])
|
||||
schema = AutoSchema(tags=["users", "orders"])
|
||||
...
|
||||
```
|
||||
|
||||
|
@ -68,7 +68,7 @@ may be overridden if needed](https://www.django-rest-framework.org/api-guide/sch
|
|||
|
||||
```python
|
||||
class MyOrders(APIView):
|
||||
schema = AutoSchema(component_name="OrderDetails")
|
||||
schema = AutoSchema(component_name="OrderDetails")
|
||||
```
|
||||
|
||||
## More Public API
|
||||
|
@ -118,10 +118,11 @@ class SitesSearchView(generics.ListAPIView):
|
|||
by a search against the site name or location. (Location searches are
|
||||
matched against the region and country names.)
|
||||
"""
|
||||
|
||||
queryset = Sites.objects.all()
|
||||
serializer_class = SitesSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['site_name', 'location__region', 'location__country']
|
||||
search_fields = ["site_name", "location__region", "location__country"]
|
||||
```
|
||||
|
||||
### Searches against annotate fields
|
||||
|
@ -135,14 +136,25 @@ class PublisherSearchView(generics.ListAPIView):
|
|||
Search for publishers, optionally filtering the search against the average
|
||||
rating of all their books.
|
||||
"""
|
||||
queryset = Publisher.objects.annotate(avg_rating=Avg('book__rating'))
|
||||
|
||||
queryset = Publisher.objects.annotate(avg_rating=Avg("book__rating"))
|
||||
serializer_class = PublisherSerializer
|
||||
filter_backends = [filters.SearchFilter]
|
||||
search_fields = ['avg_rating']
|
||||
search_fields = ["avg_rating"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### `serializers.NullBooleanField`
|
||||
|
||||
`serializers.NullBooleanField` is now pending deprecation, and will be removed in 3.14.
|
||||
|
||||
Instead use `serializers.BooleanField` field and set `allow_null=True` which does the same thing.
|
||||
|
||||
---
|
||||
|
||||
## Funding
|
||||
|
||||
REST framework is a *collaboratively funded project*. If you use
|
||||
|
|
55
docs/community/3.13-announcement.md
Normal file
|
@ -0,0 +1,55 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.13
|
||||
|
||||
## Django 4.0 support
|
||||
|
||||
The latest release now fully supports Django 4.0.
|
||||
|
||||
Our requirements are now:
|
||||
|
||||
* Python 3.6+
|
||||
* Django 4.0, 3.2, 3.1, 2.2 (LTS)
|
||||
|
||||
## Fields arguments are now keyword-only
|
||||
|
||||
When instantiating fields on serializers, you should always use keyword arguments,
|
||||
such as `serializers.CharField(max_length=200)`. This has always been the case,
|
||||
and all the examples that we have in the documentation use keyword arguments,
|
||||
rather than positional arguments.
|
||||
|
||||
From REST framework 3.13 onwards, this is now *explicitly enforced*.
|
||||
|
||||
The most feasible cases where users might be accidentally omitting the keyword arguments
|
||||
are likely in the composite fields, `ListField` and `DictField`. For instance...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(serializers.CharField())
|
||||
```
|
||||
|
||||
They must now use the more explicit keyword argument style...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(child=serializers.CharField())
|
||||
```
|
||||
|
||||
This change has been made because using positional arguments here *does not* result in the expected behaviour.
|
||||
|
||||
See Pull Request [#7632](https://github.com/encode/django-rest-framework/pull/7632) for more details.
|
72
docs/community/3.14-announcement.md
Normal file
|
@ -0,0 +1,72 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.14
|
||||
|
||||
## Django 4.1 support
|
||||
|
||||
The latest release now fully supports Django 4.1, and drops support for Django 2.2.
|
||||
|
||||
Our requirements are now:
|
||||
|
||||
* Python 3.6+
|
||||
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||
|
||||
## `raise_exception` argument for `is_valid` is now keyword-only.
|
||||
|
||||
Calling `serializer_instance.is_valid(True)` is no longer acceptable syntax.
|
||||
If you'd like to use the `raise_exception` argument, you must use it as a
|
||||
keyword argument.
|
||||
|
||||
See Pull Request [#7952](https://github.com/encode/django-rest-framework/pull/7952) for more details.
|
||||
|
||||
## `ManyRelatedField` supports returning the default when the source attribute doesn't exist.
|
||||
|
||||
Previously, if you used a serializer field with `many=True` with a dot notated source field
|
||||
that didn't exist, it would raise an `AttributeError`. Now it will return the default or be
|
||||
skipped depending on the other arguments.
|
||||
|
||||
See Pull Request [#7574](https://github.com/encode/django-rest-framework/pull/7574) for more details.
|
||||
|
||||
|
||||
## Make Open API `get_reference` public.
|
||||
|
||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||
|
||||
## Change semantic of OR of two permission classes.
|
||||
|
||||
When OR-ing two permissions, the request has to pass either class's `has_permission() and has_object_permission()`.
|
||||
|
||||
Previously, both class's `has_permission()` was ignored when OR-ing two permissions together.
|
||||
|
||||
See Pull Request [#7522](https://github.com/encode/django-rest-framework/pull/7522) for more details.
|
||||
|
||||
## Minor fixes and improvements
|
||||
|
||||
There are a number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
|
||||
|
||||
---
|
||||
|
||||
## Deprecations
|
||||
|
||||
### `serializers.NullBooleanField`
|
||||
|
||||
`serializers.NullBooleanField` was moved to pending deprecation in 3.12, and deprecated in 3.13. It has now been removed from the core framework.
|
||||
|
||||
Instead use `serializers.BooleanField` field and set `allow_null=True` which does the same thing.
|
50
docs/community/3.15-announcement.md
Normal file
|
@ -0,0 +1,50 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.15
|
||||
|
||||
At the Internet, on March 15th, 2024, with 176 commits by 138 authors, we are happy to announce the release of Django REST framework 3.15.
|
||||
|
||||
## Django 5.0 and Python 3.12 support
|
||||
|
||||
The latest release now fully supports Django 5.0 and Python 3.12.
|
||||
|
||||
The current minimum versions of Django still is 3.0 and Python 3.6.
|
||||
|
||||
## Primary Support of UniqueConstraint
|
||||
|
||||
`ModelSerializer` generates validators for [UniqueConstraint](https://docs.djangoproject.com/en/4.0/ref/models/constraints/#uniqueconstraint) (both UniqueValidator and UniqueTogetherValidator)
|
||||
|
||||
## SimpleRouter non-regex matching support
|
||||
|
||||
By default the URLs created by `SimpleRouter` use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router.
|
||||
|
||||
## ZoneInfo as the primary source of timezone data
|
||||
|
||||
Dependency on pytz has been removed and deprecation warnings have been added, Django will provide ZoneInfo instances as long as USE_DEPRECATED_PYTZ is not enabled. More info on the migration can be found [in this guide](https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html).
|
||||
|
||||
## Align `SearchFilter` behaviour to `django.contrib.admin` search
|
||||
|
||||
Searches now may contain _quoted phrases_ with spaces, each phrase is considered as a single search term, and it will raise a validation error if any null-character is provided in search. See the [Filtering API guide](../api-guide/filtering.md) for more information.
|
||||
|
||||
## Other fixes and improvements
|
||||
|
||||
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour.
|
||||
|
||||
See the [release notes](release-notes.md) page for a complete listing.
|
42
docs/community/3.16-announcement.md
Normal file
|
@ -0,0 +1,42 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.16
|
||||
|
||||
At the Internet, on March 28th, 2025, we are happy to announce the release of Django REST framework 3.16.
|
||||
|
||||
## Updated Django and Python support
|
||||
|
||||
The latest release now fully supports Django 5.1 and the upcoming 5.2 LTS as well as Python 3.13.
|
||||
|
||||
The current minimum versions of Django is now 4.2 and Python 3.9.
|
||||
|
||||
## Django LoginRequiredMiddleware
|
||||
|
||||
The new `LoginRequiredMiddleware` introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behaviour can be configured via `DEFAULT_AUTHENTICATION_CLASSES`. See [our dedicated section](../api-guide/authentication.md#django-51-loginrequiredmiddleware) in the docs for more information.
|
||||
|
||||
## Improved support for UniqueConstraint
|
||||
|
||||
The generation of validators for [UniqueConstraint](https://docs.djangoproject.com/en/stable/ref/models/constraints/#uniqueconstraint) has been improved to support better nullable fields and constraints with conditions.
|
||||
|
||||
## Other fixes and improvements
|
||||
|
||||
There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour.
|
||||
|
||||
See the [release notes](release-notes.md) page for a complete listing.
|
|
@ -64,7 +64,7 @@ These are a little subtle and probably won't affect most users, but are worth un
|
|||
|
||||
### ManyToMany fields and blank=True
|
||||
|
||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
|
||||
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.
|
||||
|
||||
|
|
|
@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in
|
|||
|
||||
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
|
||||
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers].
|
||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||
|
||||
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
|
||||
|
||||
|
|
|
@ -89,7 +89,7 @@ Name | Support | PyPI pa
|
|||
---------------------------------|-------------------------------------|--------------------------------
|
||||
[Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
|
||||
[Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
|
||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
|
||||
|
||||
---
|
||||
|
@ -187,7 +187,7 @@ The full set of itemized release notes [are available here][release-notes].
|
|||
[api-blueprint]: https://apiblueprint.org/
|
||||
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
|
||||
[schema-generation]: ../api-guide/schemas/
|
||||
[api-clients]: ../topics/api-clients.md
|
||||
[api-clients]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md
|
||||
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
|
||||
[release-notes]: release-notes#34
|
||||
[metadata]: ../api-guide/metadata/#custom-metadata-classes
|
||||
|
|
|
@ -64,14 +64,10 @@ from rest_framework.schemas import get_schema_view
|
|||
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Example API',
|
||||
renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]
|
||||
title="Example API", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path('swagger/', schema_view),
|
||||
...
|
||||
]
|
||||
urlpatterns = [path("swagger/", schema_view), ...]
|
||||
```
|
||||
|
||||
There have been a large number of fixes to the schema generation. These should
|
||||
|
|
|
@ -195,5 +195,5 @@ on realtime support, for the 3.7 release.
|
|||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
||||
[api-docs]: ../topics/documenting-your-api.md
|
||||
[js-docs]: ../topics/api-clients.md#javascript-client-library
|
||||
[py-docs]: ../topics/api-clients.md#python-client-library
|
||||
[js-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#javascript-client-library
|
||||
[py-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#python-client-library
|
||||
|
|
|
@ -89,7 +89,7 @@ for a complete listing.
|
|||
|
||||
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
|
||||
|
||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||
|
||||
[funding]: funding.md
|
||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||
|
|
|
@ -65,15 +65,12 @@ from rest_framework.renderers import JSONOpenAPIRenderer
|
|||
from django.urls import path
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
renderer_classes=[JSONOpenAPIRenderer]
|
||||
title="Server Monitoring API",
|
||||
url="https://www.example.org/api/",
|
||||
renderer_classes=[JSONOpenAPIRenderer],
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path('schema.json', schema_view),
|
||||
...
|
||||
]
|
||||
urlpatterns = [path("schema.json", schema_view), ...]
|
||||
```
|
||||
|
||||
And here's how you can use the `generateschema` management command:
|
||||
|
@ -110,7 +107,7 @@ You can now compose permission classes using the and/or operators, `&` and `|`.
|
|||
For example...
|
||||
|
||||
```python
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdmin)]
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
|
||||
```
|
||||
|
||||
If you're using custom permission classes then make sure that you are subclassing
|
||||
|
|
|
@ -4,7 +4,9 @@
|
|||
>
|
||||
> — [Tim Berners-Lee][cite]
|
||||
|
||||
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
|
||||
!!! note
|
||||
|
||||
At this point in its lifespan we consider Django REST framework to be feature-complete. We focus on pull requests that track the continued development of Django versions, and generally do not accept new features or code formatting changes.
|
||||
|
||||
## Community
|
||||
|
||||
|
@ -26,25 +28,8 @@ The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines f
|
|||
|
||||
# Issues
|
||||
|
||||
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
|
||||
|
||||
Some tips on good issue reporting:
|
||||
|
||||
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
|
||||
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
|
||||
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
|
||||
|
||||
## Triaging issues
|
||||
|
||||
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to
|
||||
|
||||
* Read through the ticket - does it make sense, is it missing any context that would help explain it better?
|
||||
* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
|
||||
* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
|
||||
* If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?
|
||||
* If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.
|
||||
* Django REST framework is considered feature-complete. Please do not file requests to change behavior, unless it is required for security reasons or to maintain compatibility with upcoming Django or Python versions.
|
||||
* Feature requests will typically be closed with a recommendation that they be implemented outside the core REST framework library (e.g. as third-party libraries). This approach allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability and great documentation.
|
||||
|
||||
# Development
|
||||
|
||||
|
@ -54,11 +39,19 @@ To start developing on Django REST framework, first create a Fork from the
|
|||
Then clone your fork. The clone command will look like this, with your GitHub
|
||||
username instead of YOUR-USERNAME:
|
||||
|
||||
git clone https://github.com/YOUR-USERNAME/Spoon-Knife
|
||||
git clone https://github.com/YOUR-USERNAME/django-rest-framework
|
||||
|
||||
See GitHub's [_Fork a Repo_][how-to-fork] Guide for more help.
|
||||
|
||||
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
|
||||
You can check your contributions against these conventions each time you commit using the [pre-commit](https://pre-commit.com/) hooks, which we also run on CI.
|
||||
To set them up, first ensure you have the pre-commit tool installed, for example:
|
||||
|
||||
python -m pip install pre-commit
|
||||
|
||||
Then run:
|
||||
|
||||
pre-commit install
|
||||
|
||||
## Testing
|
||||
|
||||
|
@ -67,7 +60,7 @@ To run the tests, clone the repository, and then:
|
|||
# Setup the virtual environment
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
pip install django
|
||||
pip install -e .
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Run the tests
|
||||
|
@ -79,18 +72,6 @@ Run using a more concise output style.
|
|||
|
||||
./runtests.py -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
./runtests.py --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
./runtests.py --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
./runtests.py --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
./runtests.py MyTestCase
|
||||
|
@ -123,11 +104,11 @@ GitHub's documentation for working on pull requests is [available here][pull-req
|
|||
|
||||
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible on all supported versions of Python and Django.
|
||||
|
||||
Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
|
||||
Once you've made a pull request take a look at the build status in the GitHub interface and make sure the tests are running as you'd expect.
|
||||
|
||||
![Travis status][travis-status]
|
||||
![Build status][build-status]
|
||||
|
||||
*Above: Travis build notifications*
|
||||
*Above: build notifications*
|
||||
|
||||
## Managing compatibility issues
|
||||
|
||||
|
@ -208,9 +189,8 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
|
|||
[code-of-conduct]: https://www.djangoproject.com/conduct/
|
||||
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[so-filter]: https://stackexchange.com/filters/66475/rest-framework
|
||||
[issues]: https://github.com/encode/django-rest-framework/issues?state=open
|
||||
[pep-8]: https://www.python.org/dev/peps/pep-0008/
|
||||
[travis-status]: ../img/travis-status.png
|
||||
[build-status]: ../img/build-status.png
|
||||
[pull-requests]: https://help.github.com/articles/using-pull-requests
|
||||
[tox]: https://tox.readthedocs.io/en/latest/
|
||||
[markdown]: https://daringfireball.net/projects/markdown/basics
|
||||
|
|
|
@ -1,398 +1,398 @@
|
|||
<script>
|
||||
// Imperfect, but easier to fit in with the existing docs build.
|
||||
// Hyperlinks should point directly to the "fund." subdomain, but this'll
|
||||
// handle the nav bar links without requiring any docs build changes for the moment.
|
||||
if (window.location.hostname == "www.django-rest-framework.org") {
|
||||
window.location.replace("https://fund.django-rest-framework.org/topics/funding/");
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
.chart {
|
||||
background-color: #e3e3e3;
|
||||
background: -webkit-linear-gradient(top, #fff 0, #e3e3e3 100%);
|
||||
border: 1px solid #E6E6E6;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0px 0px 2px 0px rgba(181, 181, 181, 0.3);
|
||||
padding: 40px 0px 5px;
|
||||
position: relative;
|
||||
text-align: center;
|
||||
width: 97%;
|
||||
min-height: 255px;
|
||||
position: relative;
|
||||
top: 37px;
|
||||
margin-bottom: 20px
|
||||
}
|
||||
.quantity {
|
||||
text-align: center
|
||||
}
|
||||
.dollar {
|
||||
font-size: 19px;
|
||||
position: relative;
|
||||
top: -18px;
|
||||
}
|
||||
.price {
|
||||
font-size: 49px;
|
||||
}
|
||||
.period {
|
||||
font-size: 17px;
|
||||
position: relative;
|
||||
top: -8px;
|
||||
margin-left: 4px;
|
||||
}
|
||||
.plan-name {
|
||||
text-align: center;
|
||||
font-size: 20px;
|
||||
font-weight: 400;
|
||||
color: #777;
|
||||
border-bottom: 1px solid #d5d5d5;
|
||||
padding-bottom: 15px;
|
||||
width: 90%;
|
||||
margin: 0 auto;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.specs {
|
||||
margin-top: 20px;
|
||||
min-height: 130px;
|
||||
}
|
||||
.specs.freelancer {
|
||||
min-height: 0px;
|
||||
}
|
||||
.spec {
|
||||
font-size: 15px;
|
||||
color: #474747;
|
||||
text-align: center;
|
||||
font-weight: 300;
|
||||
margin-bottom: 13px;
|
||||
}
|
||||
.variable {
|
||||
color: #1FBEE7;
|
||||
font-weight: 400;
|
||||
}
|
||||
form.signup {
|
||||
margin-top: 35px
|
||||
}
|
||||
.clear-promo {
|
||||
padding-top: 30px
|
||||
}
|
||||
#main-content h1:first-of-type {
|
||||
margin: 0 0 50px;
|
||||
font-size: 60px;
|
||||
font-weight: 200;
|
||||
text-align: center
|
||||
}
|
||||
#main-content {
|
||||
padding-top: 10px; line-height: 23px
|
||||
}
|
||||
#main-content li {
|
||||
line-height: 23px
|
||||
}
|
||||
</style>
|
||||
|
||||
# Funding
|
||||
|
||||
If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.
|
||||
|
||||
**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.**
|
||||
|
||||
Signing up for a paid plan will:
|
||||
|
||||
* Directly contribute to faster releases, more features, and higher quality software.
|
||||
* Allow more time to be invested in documentation, issue triage, and community support.
|
||||
* Safeguard the future development of REST framework.
|
||||
|
||||
REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.
|
||||
|
||||
---
|
||||
|
||||
## What funding has enabled so far
|
||||
|
||||
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
||||
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
|
||||
* Tom Christie, the creator of Django REST framework, working on the project full-time.
|
||||
* Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.
|
||||
* A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.
|
||||
* Contracting development time for the work on the JavaScript client library and API documentation tooling.
|
||||
|
||||
---
|
||||
|
||||
## What future funding will enable
|
||||
|
||||
* Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries.
|
||||
* Better authentication defaults, possibly bringing JWT & CORs support into the core package.
|
||||
* Securing the community & operations manager position long-term.
|
||||
* Opening up and securing a part-time position to focus on ticket triage and resolution.
|
||||
* Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation.
|
||||
|
||||
Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.
|
||||
|
||||
---
|
||||
|
||||
## What our sponsors and users say
|
||||
|
||||
> As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.
|
||||
>
|
||||
> — José Padilla, Django REST framework contributor
|
||||
|
||||
|
||||
|
||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||
>
|
||||
> — Filipe Ximenes, Vinta Software
|
||||
|
||||
|
||||
|
||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
|
||||
>
|
||||
> — Andrew Conti, Django REST framework user
|
||||
|
||||
---
|
||||
|
||||
## Individual plan
|
||||
|
||||
This subscription is recommended for individuals with an interest in seeing REST framework continue to improve.
|
||||
|
||||
If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans).
|
||||
|
||||
<div class="pricing">
|
||||
<div class="span4">
|
||||
<div class="chart first">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.personal1 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Individual</div>
|
||||
<div class="specs freelancer">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
Credited on the site
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.personal1 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.personal1 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Individual"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="clear: both; padding-top: 50px"></div>
|
||||
|
||||
*Billing is monthly and you can cancel at any time.*
|
||||
|
||||
---
|
||||
|
||||
## Corporate plans
|
||||
|
||||
These subscriptions are recommended for companies and organizations using REST framework either publicly or privately.
|
||||
|
||||
In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**.
|
||||
|
||||
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
|
||||
|
||||
<div class="pricing">
|
||||
<div class="span4">
|
||||
<div class="chart first">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate1 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Basic</div>
|
||||
<div class="specs startup">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Funding page</span> ad placement
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate1 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate1 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Basic"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span4">
|
||||
<div class="chart">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate2 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Professional</div>
|
||||
<div class="specs">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Sidebar</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Priority support</span> for your engineers
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate2 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate2 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Professional"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span4">
|
||||
<div class="chart last">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate3 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Premium</div>
|
||||
<div class="specs">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Homepage</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Sidebar</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Priority support</span> for your engineers
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate3 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate3 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Premium"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="clear: both; padding-top: 50px"></div>
|
||||
|
||||
*Billing is monthly and you can cancel at any time.*
|
||||
|
||||
Once you've signed up, we will contact you via email and arrange your ad placements on the site.
|
||||
|
||||
For further enquires please contact <a href=mailto:funding@django-rest-framework.org>funding@django-rest-framework.org</a>.
|
||||
|
||||
---
|
||||
|
||||
## Accountability
|
||||
|
||||
In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns.
|
||||
|
||||
<!-- Begin MailChimp Signup Form -->
|
||||
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
|
||||
<style type="text/css">
|
||||
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||
</style>
|
||||
<div id="mc_embed_signup">
|
||||
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||
<div id="mc_embed_signup_scroll">
|
||||
<h2>Stay up to date, with our monthly progress reports...</h2>
|
||||
<div class="mc-field-group">
|
||||
<label for="mce-EMAIL">Email Address </label>
|
||||
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
|
||||
</div>
|
||||
<div id="mce-responses" class="clear">
|
||||
<div class="response" id="mce-error-response" style="display:none"></div>
|
||||
<div class="response" id="mce-success-response" style="display:none"></div>
|
||||
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
|
||||
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
|
||||
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
|
||||
<!--End mc_embed_signup-->
|
||||
|
||||
---
|
||||
|
||||
## Frequently asked questions
|
||||
|
||||
**Q: Can you issue monthly invoices?**
|
||||
A: Yes, we are happy to issue monthly invoices. Please just <a href=mailto:funding@django-rest-framework.org>email us</a> and let us know who to issue the invoice to (name and address) and which email address to send it to each month.
|
||||
|
||||
**Q: Does sponsorship include VAT?**
|
||||
A: Sponsorship is VAT exempt.
|
||||
|
||||
**Q: Do I have to sign up for a certain time period?**
|
||||
A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.
|
||||
|
||||
**Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time?**
|
||||
A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.
|
||||
|
||||
**Q: Are you only looking for corporate sponsors?**
|
||||
A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.
|
||||
|
||||
---
|
||||
|
||||
## Our sponsors
|
||||
|
||||
<div id="fundingInclude"></div>
|
||||
|
||||
<script src="https://fund.django-rest-framework.org/funding_include.js"></script>
|
||||
<script>
|
||||
// Imperfect, but easier to fit in with the existing docs build.
|
||||
// Hyperlinks should point directly to the "fund." subdomain, but this'll
|
||||
// handle the nav bar links without requiring any docs build changes for the moment.
|
||||
if (window.location.hostname == "www.django-rest-framework.org") {
|
||||
window.location.replace("https://fund.django-rest-framework.org/topics/funding/");
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
.chart {
|
||||
background-color: #e3e3e3;
|
||||
background: -webkit-linear-gradient(top, #fff 0, #e3e3e3 100%);
|
||||
border: 1px solid #E6E6E6;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0px 0px 2px 0px rgba(181, 181, 181, 0.3);
|
||||
padding: 40px 0px 5px;
|
||||
position: relative;
|
||||
text-align: center;
|
||||
width: 97%;
|
||||
min-height: 255px;
|
||||
position: relative;
|
||||
top: 37px;
|
||||
margin-bottom: 20px
|
||||
}
|
||||
.quantity {
|
||||
text-align: center
|
||||
}
|
||||
.dollar {
|
||||
font-size: 19px;
|
||||
position: relative;
|
||||
top: -18px;
|
||||
}
|
||||
.price {
|
||||
font-size: 49px;
|
||||
}
|
||||
.period {
|
||||
font-size: 17px;
|
||||
position: relative;
|
||||
top: -8px;
|
||||
margin-left: 4px;
|
||||
}
|
||||
.plan-name {
|
||||
text-align: center;
|
||||
font-size: 20px;
|
||||
font-weight: 400;
|
||||
color: #777;
|
||||
border-bottom: 1px solid #d5d5d5;
|
||||
padding-bottom: 15px;
|
||||
width: 90%;
|
||||
margin: 0 auto;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.specs {
|
||||
margin-top: 20px;
|
||||
min-height: 130px;
|
||||
}
|
||||
.specs.freelancer {
|
||||
min-height: 0px;
|
||||
}
|
||||
.spec {
|
||||
font-size: 15px;
|
||||
color: #474747;
|
||||
text-align: center;
|
||||
font-weight: 300;
|
||||
margin-bottom: 13px;
|
||||
}
|
||||
.variable {
|
||||
color: #1FBEE7;
|
||||
font-weight: 400;
|
||||
}
|
||||
form.signup {
|
||||
margin-top: 35px
|
||||
}
|
||||
.clear-promo {
|
||||
padding-top: 30px
|
||||
}
|
||||
#main-content h1:first-of-type {
|
||||
margin: 0 0 50px;
|
||||
font-size: 60px;
|
||||
font-weight: 200;
|
||||
text-align: center
|
||||
}
|
||||
#main-content {
|
||||
padding-top: 10px; line-height: 23px
|
||||
}
|
||||
#main-content li {
|
||||
line-height: 23px
|
||||
}
|
||||
</style>
|
||||
|
||||
# Funding
|
||||
|
||||
If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan.
|
||||
|
||||
**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.**
|
||||
|
||||
Signing up for a paid plan will:
|
||||
|
||||
* Directly contribute to faster releases, more features, and higher quality software.
|
||||
* Allow more time to be invested in documentation, issue triage, and community support.
|
||||
* Safeguard the future development of REST framework.
|
||||
|
||||
REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development.
|
||||
|
||||
---
|
||||
|
||||
## What funding has enabled so far
|
||||
|
||||
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
||||
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
|
||||
* Tom Christie, the creator of Django REST framework, working on the project full-time.
|
||||
* Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time.
|
||||
* A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship.
|
||||
* Contracting development time for the work on the JavaScript client library and API documentation tooling.
|
||||
|
||||
---
|
||||
|
||||
## What future funding will enable
|
||||
|
||||
* Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries.
|
||||
* Better authentication defaults, possibly bringing JWT & CORS support into the core package.
|
||||
* Securing the community & operations manager position long-term.
|
||||
* Opening up and securing a part-time position to focus on ticket triage and resolution.
|
||||
* Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation.
|
||||
|
||||
Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project.
|
||||
|
||||
---
|
||||
|
||||
## What our sponsors and users say
|
||||
|
||||
> As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem.
|
||||
>
|
||||
> — José Padilla, Django REST framework contributor
|
||||
|
||||
|
||||
|
||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||
>
|
||||
> — Filipe Ximenes, Vinta Software
|
||||
|
||||
|
||||
|
||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
|
||||
>
|
||||
> — Andrew Conti, Django REST framework user
|
||||
|
||||
---
|
||||
|
||||
## Individual plan
|
||||
|
||||
This subscription is recommended for individuals with an interest in seeing REST framework continue to improve.
|
||||
|
||||
If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans).
|
||||
|
||||
<div class="pricing">
|
||||
<div class="span4">
|
||||
<div class="chart first">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.personal1 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Individual</div>
|
||||
<div class="specs freelancer">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
Credited on the site
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.personal1 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.personal1 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Individual"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="clear: both; padding-top: 50px"></div>
|
||||
|
||||
*Billing is monthly and you can cancel at any time.*
|
||||
|
||||
---
|
||||
|
||||
## Corporate plans
|
||||
|
||||
These subscriptions are recommended for companies and organizations using REST framework either publicly or privately.
|
||||
|
||||
In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**.
|
||||
|
||||
Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day.
|
||||
|
||||
<div class="pricing">
|
||||
<div class="span4">
|
||||
<div class="chart first">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate1 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Basic</div>
|
||||
<div class="specs startup">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Funding page</span> ad placement
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate1 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate1 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Basic"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span4">
|
||||
<div class="chart">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate2 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Professional</div>
|
||||
<div class="specs">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Sidebar</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Priority support</span> for your engineers
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate2 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate2 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Professional"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span4">
|
||||
<div class="chart last">
|
||||
<div class="quantity">
|
||||
<span class="dollar">{{ symbol }}</span>
|
||||
<span class="price">{{ rates.corporate3 }}</span>
|
||||
<span class="period">/month{% if vat %} +VAT{% endif %}</span>
|
||||
</div>
|
||||
<div class="plan-name">Premium</div>
|
||||
<div class="specs">
|
||||
<div class="spec">
|
||||
Support ongoing development
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Homepage</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Sidebar</span> ad placement
|
||||
</div>
|
||||
<div class="spec">
|
||||
<span class="variable">Priority support</span> for your engineers
|
||||
</div>
|
||||
</div>
|
||||
<form class="signup" action="/signup/{{ currency }}-{{ rates.corporate3 }}/" method="POST">
|
||||
<script
|
||||
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
|
||||
data-key="{{ stripe_public }}"
|
||||
data-amount="{{ stripe_amounts.corporate3 }}"
|
||||
data-name="Django REST framework"
|
||||
data-description="Premium"
|
||||
data-currency="{{ currency }}"
|
||||
data-allow-remember-me=false
|
||||
data-billing-address=true
|
||||
data-label='Sign up'
|
||||
data-panel-label='Sign up - {% verbatim %}{{amount}}{% endverbatim %}/mo'>
|
||||
</script>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="clear: both; padding-top: 50px"></div>
|
||||
|
||||
*Billing is monthly and you can cancel at any time.*
|
||||
|
||||
Once you've signed up, we will contact you via email and arrange your ad placements on the site.
|
||||
|
||||
For further enquires please contact <a href=mailto:funding@django-rest-framework.org>funding@django-rest-framework.org</a>.
|
||||
|
||||
---
|
||||
|
||||
## Accountability
|
||||
|
||||
In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns.
|
||||
|
||||
<!-- Begin MailChimp Signup Form -->
|
||||
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
|
||||
<style type="text/css">
|
||||
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
||||
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
||||
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
||||
</style>
|
||||
<div id="mc_embed_signup">
|
||||
<form action="//encode.us13.list-manage.com/subscribe/post?u=b6b66bb5e4c7cb484a85c8dd7&id=e382ef68ef" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
||||
<div id="mc_embed_signup_scroll">
|
||||
<h2>Stay up to date, with our monthly progress reports...</h2>
|
||||
<div class="mc-field-group">
|
||||
<label for="mce-EMAIL">Email Address </label>
|
||||
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
|
||||
</div>
|
||||
<div id="mce-responses" class="clear">
|
||||
<div class="response" id="mce-error-response" style="display:none"></div>
|
||||
<div class="response" id="mce-success-response" style="display:none"></div>
|
||||
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
|
||||
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_b6b66bb5e4c7cb484a85c8dd7_e382ef68ef" tabindex="-1" value=""></div>
|
||||
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
|
||||
<!--End mc_embed_signup-->
|
||||
|
||||
---
|
||||
|
||||
## Frequently asked questions
|
||||
|
||||
**Q: Can you issue monthly invoices?**
|
||||
A: Yes, we are happy to issue monthly invoices. Please just <a href=mailto:funding@django-rest-framework.org>email us</a> and let us know who to issue the invoice to (name and address) and which email address to send it to each month.
|
||||
|
||||
**Q: Does sponsorship include VAT?**
|
||||
A: Sponsorship is VAT exempt.
|
||||
|
||||
**Q: Do I have to sign up for a certain time period?**
|
||||
A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime.
|
||||
|
||||
**Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time?**
|
||||
A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution.
|
||||
|
||||
**Q: Are you only looking for corporate sponsors?**
|
||||
A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support.
|
||||
|
||||
---
|
||||
|
||||
## Our sponsors
|
||||
|
||||
<div id="fundingInclude"></div>
|
||||
|
||||
<script src="https://fund.django-rest-framework.org/funding_include.js"></script>
|
||||
|
|
|
@ -7,15 +7,17 @@ Looking for a new Django REST Framework related role? On this site we provide a
|
|||
|
||||
* [https://www.djangoproject.com/community/jobs/][djangoproject-website]
|
||||
* [https://www.python.org/jobs/][python-org-jobs]
|
||||
* [https://django.on-remote.com][django-on-remote]
|
||||
* [https://djangogigs.com][django-gigs-com]
|
||||
* [https://djangojobs.net/jobs/][django-jobs-net]
|
||||
* [https://findwork.dev/django-rest-framework-jobs][findwork-dev]
|
||||
* [https://www.indeed.com/q-Django-jobs.html][indeed-com]
|
||||
* [https://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com]
|
||||
* [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com]
|
||||
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
|
||||
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
|
||||
* [https://remoteok.io/remote-django-jobs][remoteok-io]
|
||||
* [https://remoteok.com/remote-django-jobs][remoteok-com]
|
||||
* [https://www.remotepython.com/jobs/][remotepython-com]
|
||||
* [https://www.pyjobs.com/][pyjobs-com]
|
||||
|
||||
|
||||
Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email].
|
||||
|
@ -25,15 +27,17 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram
|
|||
|
||||
[djangoproject-website]: https://www.djangoproject.com/community/jobs/
|
||||
[python-org-jobs]: https://www.python.org/jobs/
|
||||
[django-on-remote]: https://django.on-remote.com/
|
||||
[django-gigs-com]: https://djangogigs.com
|
||||
[django-jobs-net]: https://djangojobs.net/jobs/
|
||||
[findwork-dev]: https://findwork.dev/django-rest-framework-jobs
|
||||
[indeed-com]: https://www.indeed.com/q-Django-jobs.html
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/developer-jobs-using-django
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django
|
||||
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
|
||||
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
|
||||
[remoteok-io]: https://remoteok.io/remote-django-jobs
|
||||
[remoteok-com]: https://remoteok.com/remote-django-jobs
|
||||
[remotepython-com]: https://www.remotepython.com/jobs/
|
||||
[pyjobs-com]: https://www.pyjobs.com/
|
||||
[drf-funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||
[submit-pr]: https://github.com/encode/django-rest-framework
|
||||
[anna-email]: mailto:anna@django-rest-framework.org
|
||||
|
|
|
@ -13,55 +13,13 @@ The aim is to ensure that the project has a high
|
|||
|
||||
## Maintenance team
|
||||
|
||||
We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate.
|
||||
[Participating actively in the REST framework project](contributing.md) **does not require being part of the maintenance team**. Almost every important part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.
|
||||
|
||||
#### Current team
|
||||
#### Composition
|
||||
|
||||
The [maintenance team for Q4 2015](https://github.com/encode/django-rest-framework/issues/2190):
|
||||
The composition of the maintenance team is handled by [@tomchristie](https://github.com/encode/). Team members will be added as collaborators to the repository.
|
||||
|
||||
* [@tomchristie](https://github.com/encode/)
|
||||
* [@xordoquy](https://github.com/xordoquy/) (Release manager.)
|
||||
* [@carltongibson](https://github.com/carltongibson/)
|
||||
* [@kevin-brown](https://github.com/kevin-brown/)
|
||||
* [@jpadilla](https://github.com/jpadilla/)
|
||||
|
||||
#### Maintenance cycles
|
||||
|
||||
Each maintenance cycle is initiated by an issue being opened with the `Process` label.
|
||||
|
||||
* To be considered for a maintainer role simply comment against the issue.
|
||||
* Existing members must explicitly opt-in to the next cycle by check-marking their name.
|
||||
* The final decision on the incoming team will be made by `@tomchristie`.
|
||||
|
||||
Members of the maintenance team will be added as collaborators to the repository.
|
||||
|
||||
The following template should be used for the description of the issue, and serves as the formal process for selecting the team.
|
||||
|
||||
This issue is for determining the maintenance team for the *** period.
|
||||
|
||||
Please see the [Project management](https://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details.
|
||||
|
||||
---
|
||||
|
||||
#### Renewing existing members.
|
||||
|
||||
The following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period.
|
||||
|
||||
- [ ] @***
|
||||
- [ ] @***
|
||||
- [ ] @***
|
||||
- [ ] @***
|
||||
- [ ] @***
|
||||
|
||||
---
|
||||
|
||||
#### New members.
|
||||
|
||||
If you wish to be considered for this or a future date, please comment against this or subsequent issues.
|
||||
|
||||
To modify this process for future maintenance cycles make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation.
|
||||
|
||||
#### Responsibilities of team members
|
||||
#### Responsibilities
|
||||
|
||||
Team members have the following responsibilities.
|
||||
|
||||
|
@ -76,18 +34,13 @@ Further notes for maintainers:
|
|||
* Code changes should come in the form of a pull request - do not push directly to master.
|
||||
* Maintainers should typically not merge their own pull requests.
|
||||
* Each issue/pull request should have exactly one label once triaged.
|
||||
* Search for un-triaged issues with [is:open no:label][un-triaged].
|
||||
|
||||
It should be noted that participating actively in the REST framework project clearly **does not require being part of the maintenance team**. Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository.
|
||||
|
||||
---
|
||||
|
||||
## Release process
|
||||
|
||||
The release manager is selected on every quarterly maintenance cycle.
|
||||
|
||||
* The manager should be selected by `@tomchristie`.
|
||||
* The manager will then have the maintainer role added to PyPI package.
|
||||
* The release manager is selected by `@tomchristie`.
|
||||
* The release manager will then have the maintainer role added to PyPI package.
|
||||
* The previous manager will then have the maintainer role removed from the PyPI package.
|
||||
|
||||
Our PyPI releases will be handled by either the current release manager, or by `@tomchristie`. Every release should have an open issue tagged with the `Release` label and marked against the appropriate milestone.
|
||||
|
@ -112,6 +65,9 @@ The following template should be used for the description of the issue, and serv
|
|||
- [ ] `docs` Python & Django versions
|
||||
- [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations).
|
||||
- [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/__init__.py).
|
||||
- [ ] Ensure documentation validates
|
||||
- Build and serve docs `mkdocs serve`
|
||||
- Validate links `pylinkvalidate.py -P http://127.0.0.1:8000`
|
||||
- [ ] Confirm with @tomchristie that release is finalized and ready to go.
|
||||
- [ ] Ensure that release date is included in pull request.
|
||||
- [ ] Merge the release pull request.
|
||||
|
@ -195,15 +151,12 @@ If `@tomchristie` ceases to participate in the project then `@j4mie` has respons
|
|||
|
||||
The following issues still need to be addressed:
|
||||
|
||||
* Ensure `@jamie` has back-up access to the `django-rest-framework.org` domain setup and admin.
|
||||
* Document ownership of the [live example][sandbox] API.
|
||||
* Ensure `@j4mie` has back-up access to the `django-rest-framework.org` domain setup and admin.
|
||||
* Document ownership of the [mailing list][mailing-list] and IRC channel.
|
||||
* Document ownership and management of the security mailing list.
|
||||
|
||||
[bus-factor]: https://en.wikipedia.org/wiki/Bus_factor
|
||||
[un-triaged]: https://github.com/encode/django-rest-framework/issues?q=is%3Aopen+no%3Alabel
|
||||
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
|
||||
[transifex-client]: https://pypi.org/project/transifex-client/
|
||||
[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework
|
||||
|
|
|
@ -2,11 +2,13 @@
|
|||
|
||||
## Versioning
|
||||
|
||||
Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
|
||||
- **Minor** version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
|
||||
|
||||
Medium version numbers (0.x.0) may include API changes, in line with the [deprecation policy][deprecation-policy]. You should read the release notes carefully before upgrading between medium point releases.
|
||||
- **Medium** version numbers (0.x.0) may include API changes, in line with the [deprecation policy][deprecation-policy]. You should read the release notes carefully before upgrading between medium point releases.
|
||||
|
||||
Major version numbers (x.0.0) are reserved for substantial project milestones.
|
||||
- **Major** version numbers (x.0.0) are reserved for substantial project milestones.
|
||||
|
||||
As REST Framework is considered feature-complete, most releases are expected to be minor releases.
|
||||
|
||||
## Deprecation policy
|
||||
|
||||
|
@ -34,6 +36,232 @@ You can determine your currently installed version using `pip show`:
|
|||
|
||||
---
|
||||
|
||||
## 3.16.x series
|
||||
|
||||
### 3.16.0
|
||||
|
||||
**Date**: 28th March 2025
|
||||
|
||||
This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behaviour of existing features and pre-existing behaviour. Specifically, some fixes were added to around the support of `UniqueConstraint` with nullable fields which will improve built-in serializer validation.
|
||||
|
||||
## Features
|
||||
|
||||
* Add official support for Django 5.1 and its new `LoginRequiredMiddleware` in [#9514](https://github.com/encode/django-rest-framework/pull/9514) and [#9657](https://github.com/encode/django-rest-framework/pull/9657)
|
||||
* Add official Django 5.2a1 support in [#9634](https://github.com/encode/django-rest-framework/pull/9634)
|
||||
* Add support for Python 3.13 in [#9527](https://github.com/encode/django-rest-framework/pull/9527) and [#9556](https://github.com/encode/django-rest-framework/pull/9556)
|
||||
* Support Django 2.1+ test client JSON data automatically serialized in [#6511](https://github.com/encode/django-rest-framework/pull/6511) and fix a regression in [#9615](https://github.com/encode/django-rest-framework/pull/9615)
|
||||
|
||||
## Bug fixes
|
||||
|
||||
* Fix unique together validator to respect condition's fields from `UniqueConstraint` in [#9360](https://github.com/encode/django-rest-framework/pull/9360)
|
||||
* Fix raising on nullable fields part of `UniqueConstraint` in [#9531](https://github.com/encode/django-rest-framework/pull/9531)
|
||||
* Fix `unique_together` validation with source in [#9482](https://github.com/encode/django-rest-framework/pull/9482)
|
||||
* Added protections to `AttributeError` raised within properties in [#9455](https://github.com/encode/django-rest-framework/pull/9455)
|
||||
* Fix `get_template_context` to handle also lists in [#9467](https://github.com/encode/django-rest-framework/pull/9467)
|
||||
* Fix "Converter is already registered" deprecation warning. in [#9512](https://github.com/encode/django-rest-framework/pull/9512)
|
||||
* Fix noisy warning and accept integers as min/max values of `DecimalField` in [#9515](https://github.com/encode/django-rest-framework/pull/9515)
|
||||
* Fix usages of `open()` in `setup.py` in [#9661](https://github.com/encode/django-rest-framework/pull/9661)
|
||||
|
||||
## Translations
|
||||
|
||||
* Add some missing Chinese translations in [#9505](https://github.com/encode/django-rest-framework/pull/9505)
|
||||
* Fix spelling mistakes in Farsi language were corrected in [#9521](https://github.com/encode/django-rest-framework/pull/9521)
|
||||
* Fixing and adding missing Brazilian Portuguese translations in [#9535](https://github.com/encode/django-rest-framework/pull/9535)
|
||||
|
||||
## Removals
|
||||
|
||||
* Remove support for Python 3.8 in [#9670](https://github.com/encode/django-rest-framework/pull/9670)
|
||||
* Remove long deprecated code from request wrapper in [#9441](https://github.com/encode/django-rest-framework/pull/9441)
|
||||
* Remove deprecated `AutoSchema._get_reference` method in [#9525](https://github.com/encode/django-rest-framework/pull/9525)
|
||||
|
||||
## Documentation and internal changes
|
||||
|
||||
* Provide tests for hashing of `OperandHolder` in [#9437](https://github.com/encode/django-rest-framework/pull/9437)
|
||||
* Update documentation: Add `adrf` third party package in [#9198](https://github.com/encode/django-rest-framework/pull/9198)
|
||||
* Update tutorials links in Community contributions docs in [#9476](https://github.com/encode/django-rest-framework/pull/9476)
|
||||
* Fix usage of deprecated Django function in example from docs in [#9509](https://github.com/encode/django-rest-framework/pull/9509)
|
||||
* Move path converter docs into a separate section in [#9524](https://github.com/encode/django-rest-framework/pull/9524)
|
||||
* Add test covering update view without `queryset` attribute in [#9528](https://github.com/encode/django-rest-framework/pull/9528)
|
||||
* Fix Transifex link in [#9541](https://github.com/encode/django-rest-framework/pull/9541)
|
||||
* Fix example `httpie` call in docs in [#9543](https://github.com/encode/django-rest-framework/pull/9543)
|
||||
* Fix example for serializer field with choices in docs in [#9563](https://github.com/encode/django-rest-framework/pull/9563)
|
||||
* Remove extra `<>` in validators example in [#9590](https://github.com/encode/django-rest-framework/pull/9590)
|
||||
* Update `strftime` link in the docs in [#9624](https://github.com/encode/django-rest-framework/pull/9624)
|
||||
* Switch to codecov GHA in [#9618](https://github.com/encode/django-rest-framework/pull/9618)
|
||||
* Add note regarding availability of the `action` attribute in 'Introspecting ViewSet actions' docs section in [#9633](https://github.com/encode/django-rest-framework/pull/9633)
|
||||
* Improved description of allowed throttling rates in documentation in [#9640](https://github.com/encode/django-rest-framework/pull/9640)
|
||||
* Add `rest-framework-gm2m-relations` package to the list of 3rd party libraries in [#9063](https://github.com/encode/django-rest-framework/pull/9063)
|
||||
* Fix a number of typos in the test suite in the docs in [#9662](https://github.com/encode/django-rest-framework/pull/9662)
|
||||
* Add `django-pyoidc` as a third party authentication library in [#9667](https://github.com/encode/django-rest-framework/pull/9667)
|
||||
|
||||
## New Contributors
|
||||
|
||||
* [`@maerteijn`](https://github.com/maerteijn) made their first contribution in [#9198](https://github.com/encode/django-rest-framework/pull/9198)
|
||||
* [`@FraCata00`](https://github.com/FraCata00) made their first contribution in [#9444](https://github.com/encode/django-rest-framework/pull/9444)
|
||||
* [`@AlvaroVega`](https://github.com/AlvaroVega) made their first contribution in [#9451](https://github.com/encode/django-rest-framework/pull/9451)
|
||||
* [`@james`](https://github.com/james)-mchugh made their first contribution in [#9455](https://github.com/encode/django-rest-framework/pull/9455)
|
||||
* [`@ifeanyidavid`](https://github.com/ifeanyidavid) made their first contribution in [#9479](https://github.com/encode/django-rest-framework/pull/9479)
|
||||
* [`@p`](https://github.com/p)-schlickmann made their first contribution in [#9480](https://github.com/encode/django-rest-framework/pull/9480)
|
||||
* [`@akkuman`](https://github.com/akkuman) made their first contribution in [#9505](https://github.com/encode/django-rest-framework/pull/9505)
|
||||
* [`@rafaelgramoschi`](https://github.com/rafaelgramoschi) made their first contribution in [#9509](https://github.com/encode/django-rest-framework/pull/9509)
|
||||
* [`@Sinaatkd`](https://github.com/Sinaatkd) made their first contribution in [#9521](https://github.com/encode/django-rest-framework/pull/9521)
|
||||
* [`@gtkacz`](https://github.com/gtkacz) made their first contribution in [#9535](https://github.com/encode/django-rest-framework/pull/9535)
|
||||
* [`@sliverc`](https://github.com/sliverc) made their first contribution in [#9556](https://github.com/encode/django-rest-framework/pull/9556)
|
||||
* [`@gabrielromagnoli1987`](https://github.com/gabrielromagnoli1987) made their first contribution in [#9543](https://github.com/encode/django-rest-framework/pull/9543)
|
||||
* [`@cheehong1030`](https://github.com/cheehong1030) made their first contribution in [#9563](https://github.com/encode/django-rest-framework/pull/9563)
|
||||
* [`@amansharma612`](https://github.com/amansharma612) made their first contribution in [#9590](https://github.com/encode/django-rest-framework/pull/9590)
|
||||
* [`@Gluroda`](https://github.com/Gluroda) made their first contribution in [#9616](https://github.com/encode/django-rest-framework/pull/9616)
|
||||
* [`@deepakangadi`](https://github.com/deepakangadi) made their first contribution in [#9624](https://github.com/encode/django-rest-framework/pull/9624)
|
||||
* [`@EXG1O`](https://github.com/EXG1O) made their first contribution in [#9633](https://github.com/encode/django-rest-framework/pull/9633)
|
||||
* [`@decadenza`](https://github.com/decadenza) made their first contribution in [#9640](https://github.com/encode/django-rest-framework/pull/9640)
|
||||
* [`@mojtabaakbari221b`](https://github.com/mojtabaakbari221b) made their first contribution in [#9063](https://github.com/encode/django-rest-framework/pull/9063)
|
||||
* [`@mikemanger`](https://github.com/mikemanger) made their first contribution in [#9661](https://github.com/encode/django-rest-framework/pull/9661)
|
||||
* [`@gbip`](https://github.com/gbip) made their first contribution in [#9667](https://github.com/encode/django-rest-framework/pull/9667)
|
||||
|
||||
**Full Changelog**: https://github.com/encode/django-rest-framework/compare/3.15.2...3.16.0
|
||||
|
||||
## 3.15.x series
|
||||
|
||||
### 3.15.2
|
||||
|
||||
**Date**: 14th June 2024
|
||||
|
||||
* Fix potential XSS vulnerability in browsable API. [#9435](https://github.com/encode/django-rest-framework/pull/9435)
|
||||
* Revert "Ensure CursorPagination respects nulls in the ordering field". [#9381](https://github.com/encode/django-rest-framework/pull/9381)
|
||||
* Use warnings rather than logging a warning for DecimalField. [#9367](https://github.com/encode/django-rest-framework/pull/9367)
|
||||
* Remove unused code. [#9393](https://github.com/encode/django-rest-framework/pull/9393)
|
||||
* Django < 4.2 and Python < 3.8 no longer supported. [#9393](https://github.com/encode/django-rest-framework/pull/9393)
|
||||
|
||||
### 3.15.1
|
||||
|
||||
Date: 22nd March 2024
|
||||
|
||||
* Fix `SearchFilter` handling of quoted and comma separated strings, when `.get_search_terms` is being called into by a custom class. See [[#9338](https://github.com/encode/django-rest-framework/issues/9338)]
|
||||
* Revert number of 3.15.0 issues which included unintended side-effects. See [[#9331](https://github.com/encode/django-rest-framework/issues/9331)]
|
||||
|
||||
### 3.15.0
|
||||
|
||||
Date: 15th March 2024
|
||||
|
||||
* Django 5.0 and Python 3.12 support [[#9157](https://github.com/encode/django-rest-framework/pull/9157)]
|
||||
* Use POST method instead of GET to perform logout in browsable API [[9208](https://github.com/encode/django-rest-framework/pull/9208)]
|
||||
* Added jQuery 3.7.1 support & dropped previous version [[#9094](https://github.com/encode/django-rest-framework/pull/9094)]
|
||||
* Use str as default path converter [[#9066](https://github.com/encode/django-rest-framework/pull/9066)]
|
||||
* Document support for http.HTTPMethod in the @action decorator added in Python 3.11 [[#9067](https://github.com/encode/django-rest-framework/pull/9067)]
|
||||
* Update exceptions.md [[#9071](https://github.com/encode/django-rest-framework/pull/9071)]
|
||||
* Partial serializer should not have required fields [[#7563](https://github.com/encode/django-rest-framework/pull/7563)]
|
||||
* Propagate 'default' from model field to serializer field. [[#9030](https://github.com/encode/django-rest-framework/pull/9030)]
|
||||
* Allow to override child.run_validation call in ListSerializer [[#8035](https://github.com/encode/django-rest-framework/pull/8035)]
|
||||
* Align SearchFilter behaviour to django.contrib.admin search [[#9017](https://github.com/encode/django-rest-framework/pull/9017)]
|
||||
* Class name added to unknown field error [[#9019](https://github.com/encode/django-rest-framework/pull/9019)]
|
||||
* Fix: Pagination response schemas. [[#9049](https://github.com/encode/django-rest-framework/pull/9049)]
|
||||
* Fix choices in ChoiceField to support IntEnum [[#8955](https://github.com/encode/django-rest-framework/pull/8955)]
|
||||
* Fix `SearchFilter` rendering search field with invalid value [[#9023](https://github.com/encode/django-rest-framework/pull/9023)]
|
||||
* Fix OpenAPI Schema yaml rendering for `timedelta` [[#9007](https://github.com/encode/django-rest-framework/pull/9007)]
|
||||
* Fix `NamespaceVersioning` ignoring `DEFAULT_VERSION` on non-None namespaces [[#7278](https://github.com/encode/django-rest-framework/pull/7278)]
|
||||
* Added Deprecation Warnings for CoreAPI [[#7519](https://github.com/encode/django-rest-framework/pull/7519)]
|
||||
* Removed usage of `field.choices` that triggered full table load [[#8950](https://github.com/encode/django-rest-framework/pull/8950)]
|
||||
* Permit mixed casing of string values for `BooleanField` validation [[#8970](https://github.com/encode/django-rest-framework/pull/8970)]
|
||||
* Fixes `BrowsableAPIRenderer` for usage with `ListSerializer`. [[#7530](https://github.com/encode/django-rest-framework/pull/7530)]
|
||||
* Change semantic of `OR` of two permission classes [[#7522](https://github.com/encode/django-rest-framework/pull/7522)]
|
||||
* Remove dependency on `pytz` [[#8984](https://github.com/encode/django-rest-framework/pull/8984)]
|
||||
* Make set_value a method within `Serializer` [[#8001](https://github.com/encode/django-rest-framework/pull/8001)]
|
||||
* Fix URLPathVersioning reverse fallback [[#7247](https://github.com/encode/django-rest-framework/pull/7247)]
|
||||
* Warn about Decimal type in min_value and max_value arguments of DecimalField [[#8972](https://github.com/encode/django-rest-framework/pull/8972)]
|
||||
* Fix mapping for choice values [[#8968](https://github.com/encode/django-rest-framework/pull/8968)]
|
||||
* Refactor read function to use context manager for file handling [[#8967](https://github.com/encode/django-rest-framework/pull/8967)]
|
||||
* Fix: fallback on CursorPagination ordering if unset on the view [[#8954](https://github.com/encode/django-rest-framework/pull/8954)]
|
||||
* Replaced `OrderedDict` with `dict` [[#8964](https://github.com/encode/django-rest-framework/pull/8964)]
|
||||
* Refactor get_field_info method to include max_digits and decimal_places attributes in SimpleMetadata class [[#8943](https://github.com/encode/django-rest-framework/pull/8943)]
|
||||
* Implement `__eq__` for validators [[#8925](https://github.com/encode/django-rest-framework/pull/8925)]
|
||||
* Ensure CursorPagination respects nulls in the ordering field [[#8912](https://github.com/encode/django-rest-framework/pull/8912)]
|
||||
* Use ZoneInfo as primary source of timezone data [[#8924](https://github.com/encode/django-rest-framework/pull/8924)]
|
||||
* Add username search field for TokenAdmin (#8927) [[#8934](https://github.com/encode/django-rest-framework/pull/8934)]
|
||||
* Handle Nested Relation in SlugRelatedField when many=False [[#8922](https://github.com/encode/django-rest-framework/pull/8922)]
|
||||
* Bump version of jQuery to 3.6.4 & updated ref links [[#8909](https://github.com/encode/django-rest-framework/pull/8909)]
|
||||
* Support UniqueConstraint [[#7438](https://github.com/encode/django-rest-framework/pull/7438)]
|
||||
* Allow Request, Response, Field, and GenericAPIView to be subscriptable. This allows the classes to be made generic for type checking. [[#8825](https://github.com/encode/django-rest-framework/pull/8825)]
|
||||
* Feat: Add some changes to ValidationError to support django style validation errors [[#8863](https://github.com/encode/django-rest-framework/pull/8863)]
|
||||
* Fix Respect `can_read_model` permission in DjangoModelPermissions [[#8009](https://github.com/encode/django-rest-framework/pull/8009)]
|
||||
* Add SimplePathRouter [[#6789](https://github.com/encode/django-rest-framework/pull/6789)]
|
||||
* Re-prefetch related objects after updating [[#8043](https://github.com/encode/django-rest-framework/pull/8043)]
|
||||
* Fix FilePathField required argument [[#8805](https://github.com/encode/django-rest-framework/pull/8805)]
|
||||
* Raise ImproperlyConfigured exception if `basename` is not unique [[#8438](https://github.com/encode/django-rest-framework/pull/8438)]
|
||||
* Use PrimaryKeyRelatedField pkfield in openapi [[#8315](https://github.com/encode/django-rest-framework/pull/8315)]
|
||||
* replace partition with split in BasicAuthentication [[#8790](https://github.com/encode/django-rest-framework/pull/8790)]
|
||||
* Fix BooleanField's allow_null behavior [[#8614](https://github.com/encode/django-rest-framework/pull/8614)]
|
||||
* Handle Django's ValidationErrors in ListField [[#6423](https://github.com/encode/django-rest-framework/pull/6423)]
|
||||
* Remove a bit of inline CSS. Add CSP nonce where it might be required and is available [[#8783](https://github.com/encode/django-rest-framework/pull/8783)]
|
||||
* Use autocomplete widget for user selection in Token admin [[#8534](https://github.com/encode/django-rest-framework/pull/8534)]
|
||||
* Make browsable API compatible with strong CSP [[#8784](https://github.com/encode/django-rest-framework/pull/8784)]
|
||||
* Avoid inline script execution for injecting CSRF token [[#7016](https://github.com/encode/django-rest-framework/pull/7016)]
|
||||
* Mitigate global dependency on inflection [[#8017](https://github.com/encode/django-rest-framework/pull/8017)] [[#8781](https://github.com/encode/django-rest-framework/pull/8781)]
|
||||
* Register Django urls [[#8778](https://github.com/encode/django-rest-framework/pull/8778)]
|
||||
* Implemented Verbose Name Translation for TokenProxy [[#8713](https://github.com/encode/django-rest-framework/pull/8713)]
|
||||
* Properly handle OverflowError in DurationField deserialization [[#8042](https://github.com/encode/django-rest-framework/pull/8042)]
|
||||
* Fix OpenAPI operation name plural appropriately [[#8017](https://github.com/encode/django-rest-framework/pull/8017)]
|
||||
* Represent SafeString as plain string on schema rendering [[#8429](https://github.com/encode/django-rest-framework/pull/8429)]
|
||||
* Fix #8771 - Checking for authentication even if `_ignore_model_permissions = True` [[#8772](https://github.com/encode/django-rest-framework/pull/8772)]
|
||||
* Fix 404 when page query parameter is empty string [[#8578](https://github.com/encode/django-rest-framework/pull/8578)]
|
||||
* Fixes instance check in ListSerializer.to_representation [[#8726](https://github.com/encode/django-rest-framework/pull/8726)] [[#8727](https://github.com/encode/django-rest-framework/pull/8727)]
|
||||
* FloatField will crash if the input is a number that is too big [[#8725](https://github.com/encode/django-rest-framework/pull/8725)]
|
||||
* Add missing DurationField to SimpleMetadata label_lookup [[#8702](https://github.com/encode/django-rest-framework/pull/8702)]
|
||||
* Add support for Python 3.11 [[#8752](https://github.com/encode/django-rest-framework/pull/8752)]
|
||||
* Make request consistently available in pagination classes [[#8764](https://github.com/encode/django-rest-framework/pull/9764)]
|
||||
* Possibility to remove trailing zeros on DecimalFields representation [[#6514](https://github.com/encode/django-rest-framework/pull/6514)]
|
||||
* Add a method for getting serializer field name (OpenAPI) [[#7493](https://github.com/encode/django-rest-framework/pull/7493)]
|
||||
* Add `__eq__` method for `OperandHolder` class [[#8710](https://github.com/encode/django-rest-framework/pull/8710)]
|
||||
* Avoid importing `django.test` package when not testing [[#8699](https://github.com/encode/django-rest-framework/pull/8699)]
|
||||
* Preserve exception messages for wrapped Django exceptions [[#8051](https://github.com/encode/django-rest-framework/pull/8051)]
|
||||
* Include `examples` and `format` to OpenAPI schema of CursorPagination [[#8687](https://github.com/encode/django-rest-framework/pull/8687)] [[#8686](https://github.com/encode/django-rest-framework/pull/8686)]
|
||||
* Fix infinite recursion with deepcopy on Request [[#8684](https://github.com/encode/django-rest-framework/pull/8684)]
|
||||
* Refactor: Replace try/except with contextlib.suppress() [[#8676](https://github.com/encode/django-rest-framework/pull/8676)]
|
||||
* Minor fix to SerializeMethodField docstring [[#8629](https://github.com/encode/django-rest-framework/pull/8629)]
|
||||
* Minor refactor: Unnecessary use of list() function [[#8672](https://github.com/encode/django-rest-framework/pull/8672)]
|
||||
* Unnecessary list comprehension [[#8670](https://github.com/encode/django-rest-framework/pull/8670)]
|
||||
* Use correct class to indicate present deprecation [[#8665](https://github.com/encode/django-rest-framework/pull/8665)]
|
||||
|
||||
## 3.14.x series
|
||||
|
||||
### 3.14.0
|
||||
|
||||
Date: 22nd September 2022
|
||||
|
||||
* Django 2.2 is no longer supported. [[#8662](https://github.com/encode/django-rest-framework/pull/8662)]
|
||||
* Django 4.1 compatibility. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)]
|
||||
* Add `--api-version` CLI option to `generateschema` management command. [[#8663](https://github.com/encode/django-rest-framework/pull/8663)]
|
||||
* Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)]
|
||||
* Stop calling `set_context` on Validators. [[#8589](https://github.com/encode/django-rest-framework/pull/8589)]
|
||||
* Return `NotImplemented` from `ErrorDetails.__ne__`. [[#8538](https://github.com/encode/django-rest-framework/pull/8538)]
|
||||
* Don't evaluate `DateTimeField.default_timezone` when a custom timezone is set. [[#8531](https://github.com/encode/django-rest-framework/pull/8531)]
|
||||
* Make relative URLs clickable in Browsable API. [[#8464](https://github.com/encode/django-rest-framework/pull/8464)]
|
||||
* Support `ManyRelatedField` falling back to the default value when the attribute specified by dot notation doesn't exist. Matches `ManyRelatedField.get_attribute` to `Field.get_attribute`. [[#7574](https://github.com/encode/django-rest-framework/pull/7574)]
|
||||
* Make `schemas.openapi.get_reference` public. [[#7515](https://github.com/encode/django-rest-framework/pull/7515)]
|
||||
* Make `ReturnDict` support `dict` union operators on Python 3.9 and later. [[#8302](https://github.com/encode/django-rest-framework/pull/8302)]
|
||||
* Update throttling to check if `request.user` is set before checking if the user is authenticated. [[#8370](https://github.com/encode/django-rest-framework/pull/8370)]
|
||||
|
||||
## 3.13.x series
|
||||
|
||||
### 3.13.1
|
||||
|
||||
Date: 15th December 2021
|
||||
|
||||
* Revert schema naming changes with function based `@api_view`. [#8297]
|
||||
|
||||
### 3.13.0
|
||||
|
||||
Date: 13th December 2021
|
||||
|
||||
* Django 4.0 compatibility. [#8178]
|
||||
* Add `max_length` and `min_length` options to `ListSerializer`. [#8165]
|
||||
* Add `get_request_serializer` and `get_response_serializer` hooks to `AutoSchema`. [#7424]
|
||||
* Fix OpenAPI representation of null-able read only fields. [#8116]
|
||||
* Respect `UNICODE_JSON` setting in API schema outputs. [#7991]
|
||||
* Fix for `RemoteUserAuthentication`. [#7158]
|
||||
* Make Field constructors keyword-only. [#7632]
|
||||
|
||||
---
|
||||
|
||||
## 3.12.x series
|
||||
|
||||
### 3.12.4
|
||||
|
@ -116,6 +344,7 @@ Date: 28th September 2020
|
|||
* Fix `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` when source field is actually a property. [#7142]
|
||||
* `Token.generate_key` is now a class method. [#7502]
|
||||
* `@action` warns if method is wrapped in a decorator that does not preserve information using `@functools.wraps`. [#7098]
|
||||
* Deprecate `serializers.NullBooleanField` in favour of `serializers.BooleanField` with `allow_null=True` [#7122]
|
||||
|
||||
---
|
||||
|
||||
|
@ -264,7 +493,11 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
|
|||
class NullableCharField(serializers.CharField):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.validators = [v for v in self.validators if not isinstance(v, ProhibitNullCharactersValidator)]
|
||||
self.validators = [
|
||||
v
|
||||
for v in self.validators
|
||||
if not isinstance(v, ProhibitNullCharactersValidator)
|
||||
]
|
||||
```
|
||||
* Add `OpenAPIRenderer` and `generate_schema` management command. [#6229][gh6229]
|
||||
* Add OpenAPIRenderer by default, and add schema docs. [#6233][gh6233]
|
||||
|
@ -279,7 +512,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
|
|||
* Allow hashing of ErrorDetail. [#5932][gh5932]
|
||||
* Correct schema parsing for JSONField [#5878][gh5878]
|
||||
* Render descriptions (from help_text) using safe [#5869][gh5869]
|
||||
* Removed input value from deault_error_message [#5881][gh5881]
|
||||
* Removed input value from default_error_message [#5881][gh5881]
|
||||
* Added min_value/max_value support in DurationField [#5643][gh5643]
|
||||
* Fixed instance being overwritten in pk-only optimization try/except block [#5747][gh5747]
|
||||
* Fixed AttributeError from items filter when value is None [#5981][gh5981]
|
||||
|
@ -900,7 +1133,7 @@ See the [release announcement][3.6-release].
|
|||
* description.py codes and tests removal. ([#4153][gh4153])
|
||||
* Wrap guardian.VERSION in tuple. ([#4149][gh4149])
|
||||
* Refine validator for fields with <source=> kwargs. ([#4146][gh4146])
|
||||
* Fix None values representation in childs of ListField, DictField. ([#4118][gh4118])
|
||||
* Fix None values representation in children of ListField, DictField. ([#4118][gh4118])
|
||||
* Resolve TimeField representation for midnight value. ([#4107][gh4107])
|
||||
* Set proper status code in AdminRenderer for the redirection after POST/DELETE requests. ([#4106][gh4106])
|
||||
* TimeField render returns None instead of 00:00:00. ([#4105][gh4105])
|
||||
|
@ -908,7 +1141,7 @@ See the [release announcement][3.6-release].
|
|||
* Prevent raising exception when limit is 0. ([#4098][gh4098])
|
||||
* TokenAuthentication: Allow custom keyword in the header. ([#4097][gh4097])
|
||||
* Handle incorrectly padded HTTP basic auth header. ([#4090][gh4090])
|
||||
* LimitOffset pagination crashes Browseable API when limit=0. ([#4079][gh4079])
|
||||
* LimitOffset pagination crashes Browsable API when limit=0. ([#4079][gh4079])
|
||||
* Fixed DecimalField arbitrary precision support. ([#4075][gh4075])
|
||||
* Added support for custom CSRF cookie names. ([#4049][gh4049])
|
||||
* Fix regression introduced by #4035. ([#4041][gh4041])
|
||||
|
|
|
@ -14,142 +14,9 @@ We aim to make creating third party packages as easy as possible, whilst keeping
|
|||
|
||||
If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the [Mailing List][discussion-group].
|
||||
|
||||
## How to create a Third Party Package
|
||||
## Creating a Third Party Package
|
||||
|
||||
### Creating your package
|
||||
|
||||
You can use [this cookiecutter template][cookiecutter] for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.
|
||||
|
||||
Note: Let us know if you have an alternate cookiecutter package so we can also link to it.
|
||||
|
||||
#### Running the initial cookiecutter command
|
||||
|
||||
To run the initial cookiecutter command, you'll first need to install the Python `cookiecutter` package.
|
||||
|
||||
$ pip install cookiecutter
|
||||
|
||||
Once `cookiecutter` is installed just run the following to create a new project.
|
||||
|
||||
$ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework
|
||||
|
||||
You'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.
|
||||
|
||||
full_name (default is "Your full name here")? Johnny Appleseed
|
||||
email (default is "you@example.com")? jappleseed@example.com
|
||||
github_username (default is "yourname")? jappleseed
|
||||
pypi_project_name (default is "dj-package")? djangorestframework-custom-auth
|
||||
repo_name (default is "dj-package")? django-rest-framework-custom-auth
|
||||
app_name (default is "djpackage")? custom_auth
|
||||
project_short_description (default is "Your project description goes here")?
|
||||
year (default is "2014")?
|
||||
version (default is "0.1.0")?
|
||||
|
||||
#### Getting it onto GitHub
|
||||
|
||||
To put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository [here][new-repo]. If you need help, check out the [Create A Repo][create-a-repo] article on GitHub.
|
||||
|
||||
|
||||
#### Adding to Travis CI
|
||||
|
||||
We recommend using [Travis CI][travis-ci], a hosted continuous integration service which integrates well with GitHub and is free for public repositories.
|
||||
|
||||
To get started with Travis CI, [sign in][travis-ci] with your GitHub account. Once you're signed in, go to your [profile page][travis-profile] and enable the service hook for the repository you want.
|
||||
|
||||
If you use the cookiecutter template, your project will already contain a `.travis.yml` file which Travis CI will use to build your project and run tests. By default, builds are triggered every time you push to your repository or create Pull Request.
|
||||
|
||||
#### Uploading to PyPI
|
||||
|
||||
Once you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via `pip`.
|
||||
|
||||
You must [register][pypi-register] an account before publishing to PyPI.
|
||||
|
||||
To register your package on PyPI run the following command.
|
||||
|
||||
$ python setup.py register
|
||||
|
||||
If this is the first time publishing to PyPI, you'll be prompted to login.
|
||||
|
||||
Note: Before publishing you'll need to make sure you have the latest pip that supports `wheel` as well as install the `wheel` package.
|
||||
|
||||
$ pip install --upgrade pip
|
||||
$ pip install wheel
|
||||
|
||||
After this, every time you want to release a new version on PyPI just run the following command.
|
||||
|
||||
$ python setup.py publish
|
||||
You probably want to also tag the version now:
|
||||
git tag -a {0} -m 'version 0.1.0'
|
||||
git push --tags
|
||||
|
||||
After releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.
|
||||
|
||||
We recommend to follow [Semantic Versioning][semver] for your package's versions.
|
||||
|
||||
### Development
|
||||
|
||||
#### Version requirements
|
||||
|
||||
The cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, `tox.ini`, `.travis.yml`, and `setup.py` to match the set of versions you wish to support.
|
||||
|
||||
#### Tests
|
||||
|
||||
The cookiecutter template includes a `runtests.py` which uses the `pytest` package as a test runner.
|
||||
|
||||
Before running, you'll need to install a couple test requirements.
|
||||
|
||||
$ pip install -r requirements.txt
|
||||
|
||||
Once requirements installed, you can run `runtests.py`.
|
||||
|
||||
$ ./runtests.py
|
||||
|
||||
Run using a more concise output style.
|
||||
|
||||
$ ./runtests.py -q
|
||||
|
||||
Run the tests using a more concise output style, no coverage, no flake8.
|
||||
|
||||
$ ./runtests.py --fast
|
||||
|
||||
Don't run the flake8 code linting.
|
||||
|
||||
$ ./runtests.py --nolint
|
||||
|
||||
Only run the flake8 code linting, don't run the tests.
|
||||
|
||||
$ ./runtests.py --lintonly
|
||||
|
||||
Run the tests for a given test case.
|
||||
|
||||
$ ./runtests.py MyTestCase
|
||||
|
||||
Run the tests for a given test method.
|
||||
|
||||
$ ./runtests.py MyTestCase.test_this_method
|
||||
|
||||
Shorter form to run the tests for a given test method.
|
||||
|
||||
$ ./runtests.py test_this_method
|
||||
|
||||
To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using `tox`. [Tox][tox-docs] is a generic virtualenv management and test command line tool.
|
||||
|
||||
First, install `tox` globally.
|
||||
|
||||
$ pip install tox
|
||||
|
||||
To run `tox`, just simply run:
|
||||
|
||||
$ tox
|
||||
|
||||
To run a particular `tox` environment:
|
||||
|
||||
$ tox -e envlist
|
||||
|
||||
`envlist` is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:
|
||||
|
||||
$ tox -l
|
||||
|
||||
#### Version compatibility
|
||||
### Version compatibility
|
||||
|
||||
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
|
||||
|
||||
|
@ -165,7 +32,7 @@ We suggest adding your package to the [REST Framework][rest-framework-grid] grid
|
|||
|
||||
#### Adding to the Django REST framework docs
|
||||
|
||||
Create a [Pull Request][drf-create-pr] or [Issue][drf-create-issue] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Packages][third-party-packages] section.
|
||||
Create a [Pull Request][drf-create-pr] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Packages][third-party-packages] section.
|
||||
|
||||
#### Announce on the discussion group.
|
||||
|
||||
|
@ -177,7 +44,11 @@ Django REST Framework has a growing community of developers, packages, and resou
|
|||
|
||||
Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid].
|
||||
|
||||
To submit new content, [open an issue][drf-create-issue] or [create a pull request][drf-create-pr].
|
||||
To submit new content, [create a pull request][drf-create-pr].
|
||||
|
||||
## Async Support
|
||||
|
||||
* [adrf](https://github.com/em1208/adrf) - Async support, provides async Views, ViewSets, and Serializers.
|
||||
|
||||
### Authentication
|
||||
|
||||
|
@ -187,10 +58,11 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
|
||||
* [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism.
|
||||
* [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
|
||||
* [django-rest-auth][django-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
|
||||
* [dj-rest-auth][dj-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
|
||||
* [drf-oidc-auth][drf-oidc-auth] - Implements OpenID Connect token authentication for DRF.
|
||||
* [drfpasswordless][drfpasswordless] - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.
|
||||
* [django-rest-authemail][django-rest-authemail] - Provides a RESTful API for user signup and authentication using email addresses.
|
||||
* [dango-pyoidc][django-pyoidc] adds support for OpenID Connect (OIDC) authentication.
|
||||
|
||||
### Permissions
|
||||
|
||||
|
@ -239,6 +111,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
|
||||
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
|
||||
* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
|
||||
* [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request
|
||||
|
||||
### Renderers
|
||||
|
||||
|
@ -253,10 +126,11 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters.
|
||||
* [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.
|
||||
* [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values.
|
||||
* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
|
||||
* [django-rest-framework-guardian2][django-rest-framework-guardian2] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
|
||||
|
||||
### Misc
|
||||
|
||||
* [drf-sendables][drf-sendables] - User messages for Django REST Framework
|
||||
* [cookiecutter-django-rest][cookiecutter-django-rest] - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome.
|
||||
* [djangorestrelationalhyperlink][djangorestrelationalhyperlink] - A hyperlinked serializer that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
|
||||
* [django-rest-framework-proxy][django-rest-framework-proxy] - Proxy to redirect incoming request to another API server.
|
||||
|
@ -280,20 +154,27 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
|
||||
* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
|
||||
* [fast-drf] - A model based library for making API development faster and easier.
|
||||
* [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework.
|
||||
* [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints.
|
||||
* [drf-api-action][drf-api-action] - uses the power of DRF also as a library functions
|
||||
|
||||
### Customization
|
||||
|
||||
* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort.
|
||||
* [drf-redesign][drf-redesign] - A project that gives a fresh look to the browse-able API using Bootstrap 5.
|
||||
* [drf-material][drf-material] - A project that gives a sleek and elegant look to the browsable API using Material Design.
|
||||
|
||||
[drf-sendables]: https://github.com/amikrop/drf-sendables
|
||||
[cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
|
||||
[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
|
||||
[new-repo]: https://github.com/new
|
||||
[create-a-repo]: https://help.github.com/articles/create-a-repo/
|
||||
[travis-ci]: https://travis-ci.org
|
||||
[travis-profile]: https://travis-ci.org/profile
|
||||
[pypi-register]: https://pypi.org/account/register/
|
||||
[semver]: https://semver.org/
|
||||
[tox-docs]: https://tox.readthedocs.io/en/latest/
|
||||
[drf-compat]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/compat.py
|
||||
[rest-framework-grid]: https://www.djangopackages.com/grids/g/django-rest-framework/
|
||||
[drf-create-pr]: https://github.com/encode/django-rest-framework/compare
|
||||
[drf-create-issue]: https://github.com/encode/django-rest-framework/issues/new
|
||||
[authentication]: ../api-guide/authentication.md
|
||||
[permissions]: ../api-guide/permissions.md
|
||||
[third-party-packages]: ../topics/third-party-packages/#existing-third-party-packages
|
||||
|
@ -318,6 +199,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[wq.db.rest]: https://wq.io/docs/about-rest
|
||||
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
|
||||
[nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser
|
||||
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
||||
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
|
||||
[rest-pandas]: https://github.com/wq/django-rest-pandas
|
||||
|
@ -328,7 +210,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[gaiarestframework]: https://github.com/AppsFuel/gaiarestframework
|
||||
[drf-extensions]: https://github.com/chibisov/drf-extensions
|
||||
[ember-django-adapter]: https://github.com/dustinfarris/ember-django-adapter
|
||||
[django-rest-auth]: https://github.com/Tivix/django-rest-auth/
|
||||
[dj-rest-auth]: https://github.com/iMerica/dj-rest-auth
|
||||
[django-versatileimagefield]: https://github.com/WGBH/django-versatileimagefield
|
||||
[django-versatileimagefield-drf-docs]:https://django-versatileimagefield.readthedocs.io/en/latest/drf_integration.html
|
||||
[drf-tracking]: https://github.com/aschn/drf-tracking
|
||||
|
@ -336,7 +218,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||
[django-url-filter]: https://github.com/miki725/django-url-filter
|
||||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||
[drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/
|
||||
[django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms
|
||||
[djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api
|
||||
|
@ -360,7 +242,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses
|
||||
[django-restql]: https://github.com/yezyilomo/django-restql
|
||||
[djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt
|
||||
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||
[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2
|
||||
[drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler
|
||||
[djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/
|
||||
[django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf
|
||||
|
@ -370,3 +252,10 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[graphwrap]: https://github.com/PaulGilmartin/graph_wrap
|
||||
[rest-framework-actions]: https://github.com/AlexisMunera98/rest-framework-actions
|
||||
[fast-drf]: https://github.com/iashraful/fast-drf
|
||||
[django-requestlogs]: https://github.com/Raekkeri/django-requestlogs
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
[drf-api-action]: https://github.com/Ori-Roza/drf-api-action
|
||||
[drf-restwind]: https://github.com/youzarsiph/drf-restwind
|
||||
[drf-redesign]: https://github.com/youzarsiph/drf-redesign
|
||||
[drf-material]: https://github.com/youzarsiph/drf-material
|
||||
[django-pyoidc]: https://github.com/makinacorpus/django_pyoidc
|
||||
|
|
|
@ -12,19 +12,22 @@ There are a wide range of resources available for learning and using Django REST
|
|||
<img src="../../img/books/tsd-cover.png"/>
|
||||
</a>
|
||||
<a class="book-cover" href="https://djangoforapis.com">
|
||||
<img src="../../img/books/dfa-cover.jpg"/>
|
||||
<img src="../../img/books/dfa-40-cover.jpg"/>
|
||||
</a>
|
||||
<a class="book-cover" href="https://books.agiliq.com/projects/django-api-polls-tutorial/en/latest/">
|
||||
<img src="../../img/books/bda-cover.png"/>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Courses
|
||||
|
||||
* [Developing RESTful APIs with Django REST Framework][developing-restful-apis-with-django-rest-framework]
|
||||
|
||||
## Tutorials
|
||||
|
||||
* [Beginner's Guide to the Django REST Framework][beginners-guide-to-the-django-rest-framework]
|
||||
* [Django REST Framework - An Introduction][drf-an-intro]
|
||||
* [Django REST Framework Tutorial][drf-tutorial]
|
||||
* [Django REST Framework Course][django-rest-framework-course]
|
||||
* [Building a RESTful API with Django REST Framework][building-a-restful-api-with-drf]
|
||||
* [Getting Started with Django REST Framework and AngularJS][getting-started-with-django-rest-framework-and-angularjs]
|
||||
* [End to End Web App with Django REST Framework & AngularJS][end-to-end-web-app-with-django-rest-framework-angularjs]
|
||||
|
@ -35,8 +38,10 @@ There are a wide range of resources available for learning and using Django REST
|
|||
* [Check Credentials Using Django REST Framework][check-credentials-using-django-rest-framework]
|
||||
* [Creating a Production Ready API with Python and Django REST Framework – Part 1][creating-a-production-ready-api-with-python-and-drf-part1]
|
||||
* [Creating a Production Ready API with Python and Django REST Framework – Part 2][creating-a-production-ready-api-with-python-and-drf-part2]
|
||||
* [Django REST Framework Tutorial - Build a Blog API][django-rest-framework-tutorial-build-a-blog]
|
||||
* [Django REST Framework & React Tutorial - Build a Todo List API][django-rest-framework-react-tutorial-build-a-todo-list]
|
||||
* [Creating a Production Ready API with Python and Django REST Framework – Part 3][creating-a-production-ready-api-with-python-and-drf-part3]
|
||||
* [Creating a Production Ready API with Python and Django REST Framework – Part 4][creating-a-production-ready-api-with-python-and-drf-part4]
|
||||
* [Django Polls Tutorial API][django-polls-api]
|
||||
* [Django REST Framework Tutorial: Todo API][django-rest-framework-todo-api]
|
||||
* [Tutorial: Django REST with React (Django 2.0)][django-rest-react-valentinog]
|
||||
|
||||
|
||||
|
@ -45,11 +50,11 @@ There are a wide range of resources available for learning and using Django REST
|
|||
### Talks
|
||||
|
||||
* [Level Up! Rethinking the Web API Framework][pycon-us-2017]
|
||||
* [How to Make a Full Fledged REST API with Django OAuth Toolkit][full-fledged-rest-api-with-django-oauth-tookit]
|
||||
* [How to Make a Full Fledged REST API with Django OAuth Toolkit][full-fledged-rest-api-with-django-oauth-toolkit]
|
||||
* [Django REST API - So Easy You Can Learn It in 25 Minutes][django-rest-api-so-easy]
|
||||
* [Tom Christie about Django Rest Framework at Django: Under The Hood][django-under-hood-2014]
|
||||
* [Django REST Framework: Schemas, Hypermedia & Client Libraries][pycon-uk-2016]
|
||||
|
||||
* [Finally Understand Authentication in Django REST Framework][django-con-2018]
|
||||
|
||||
### Tutorials
|
||||
|
||||
|
@ -76,6 +81,7 @@ There are a wide range of resources available for learning and using Django REST
|
|||
* [Chatbot Using Django REST Framework + api.ai + Slack — Part 1/3][chatbot-using-drf-part1]
|
||||
* [New Django Admin with DRF and EmberJS... What are the News?][new-django-admin-with-drf-and-emberjs]
|
||||
* [Blog posts about Django REST Framework][medium-django-rest-framework]
|
||||
* [Implementing Rest APIs With Embedded Privacy][doordash-implementing-rest-apis]
|
||||
|
||||
### Documentations
|
||||
* [Classy Django REST Framework][cdrf.co]
|
||||
|
@ -95,10 +101,9 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
|
|||
[ember-and-django-part 1-video]: http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1
|
||||
[django-rest-framework-part-1-video]: http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1
|
||||
[web-api-performance-profiling-django-rest-framework]: https://www.dabapps.com/blog/api-performance-profiling-django-rest-framework/
|
||||
[api-development-with-django-and-django-rest-framework]: https://bnotions.com/api-development-with-django-and-django-rest-framework/
|
||||
[api-development-with-django-and-django-rest-framework]: https://bnotions.com/news-and-insights/api-development-with-django-and-django-rest-framework/
|
||||
[cdrf.co]:http://www.cdrf.co
|
||||
[medium-django-rest-framework]: https://medium.com/django-rest-framework
|
||||
[django-rest-framework-course]: https://teamtreehouse.com/library/django-rest-framework
|
||||
[pycon-uk-2016]: https://www.youtube.com/watch?v=FjmiGh7OqVg
|
||||
[django-under-hood-2014]: https://www.youtube.com/watch?v=3cSsbe-tA0E
|
||||
[integrating-pandas-drf-and-bokeh]: https://web.archive.org/web/20180104205117/http://machinalis.com/blog/pandas-django-rest-framework-bokeh/
|
||||
|
@ -110,12 +115,14 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
|
|||
[chatbot-using-drf-part1]: https://chatbotslife.com/chatbot-using-django-rest-framework-api-ai-slack-part-1-3-69c7e38b7b1e#.g2aceuncf
|
||||
[new-django-admin-with-drf-and-emberjs]: https://blog.levit.be/new-django-admin-with-emberjs-what-are-the-news/
|
||||
[drf-schema]: https://drf-schema-adapter.readthedocs.io/en/latest/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part1]: https://www.andreagrandi.it/2016/09/28/creating-production-ready-api-python-django-rest-framework-part-1/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part2]: https://www.andreagrandi.it/2016/10/01/creating-a-production-ready-api-with-python-and-django-rest-framework-part-2/
|
||||
[django-rest-framework-tutorial-build-a-blog]: https://wsvincent.com/django-rest-framework-tutorial/
|
||||
[django-rest-framework-react-tutorial-build-a-todo-list]: https://wsvincent.com/django-rest-framework-react-tutorial/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part1]: https://www.andreagrandi.it/posts/creating-production-ready-api-python-django-rest-framework-part-1/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part2]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-2/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part3]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-3/
|
||||
[creating-a-production-ready-api-with-python-and-drf-part4]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-4/
|
||||
[django-polls-api]: https://learndjango.com/tutorials/django-polls-tutorial-api
|
||||
[django-rest-framework-todo-api]: https://learndjango.com/tutorials/django-rest-framework-tutorial-todo-api
|
||||
[django-rest-api-so-easy]: https://www.youtube.com/watch?v=cqP758k1BaQ
|
||||
[full-fledged-rest-api-with-django-oauth-tookit]: https://www.youtube.com/watch?v=M6Ud3qC2tTk
|
||||
[full-fledged-rest-api-with-django-oauth-toolkit]: https://www.youtube.com/watch?v=M6Ud3qC2tTk
|
||||
[drf-in-your-pjs]: https://www.youtube.com/watch?v=xMtHsWa72Ww
|
||||
[building-a-rest-api-using-django-and-drf]: https://www.youtube.com/watch?v=PwssEec3IRw
|
||||
[drf-tutorials]: https://www.youtube.com/watch?v=axRCBgbOJp8&list=PLJtp8Jm8EDzjgVg9vVyIUMoGyqtegj7FH
|
||||
|
@ -128,3 +135,6 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
|
|||
[anna-email]: mailto:anna@django-rest-framework.org
|
||||
[pycon-us-2017]: https://www.youtube.com/watch?v=Rk6MHZdust4
|
||||
[django-rest-react-valentinog]: https://www.valentinog.com/blog/tutorial-api-django-rest-react/
|
||||
[doordash-implementing-rest-apis]: https://doordash.engineering/2013/10/07/implementing-rest-apis-with-embedded-privacy/
|
||||
[developing-restful-apis-with-django-rest-framework]: https://testdriven.io/courses/django-rest-framework/
|
||||
[django-con-2018]: https://youtu.be/pY-oje5b5Qk?si=AOU6tLi0IL1_pVzq
|
|
@ -1,231 +0,0 @@
|
|||
# Tutorial 7: Schemas & client libraries
|
||||
|
||||
A schema is a machine-readable document that describes the available API
|
||||
endpoints, their URLS, and what operations they support.
|
||||
|
||||
Schemas can be a useful tool for auto-generated documentation, and can also
|
||||
be used to drive dynamic client libraries that can interact with the API.
|
||||
|
||||
## Core API
|
||||
|
||||
In order to provide schema support REST framework uses [Core API][coreapi].
|
||||
|
||||
Core API is a document specification for describing APIs. It is used to provide
|
||||
an internal representation format of the available endpoints and possible
|
||||
interactions that an API exposes. It can either be used server-side, or
|
||||
client-side.
|
||||
|
||||
When used server-side, Core API allows an API to support rendering to a wide
|
||||
range of schema or hypermedia formats.
|
||||
|
||||
When used client-side, Core API allows for dynamically driven client libraries
|
||||
that can interact with any API that exposes a supported schema or hypermedia
|
||||
format.
|
||||
|
||||
## Adding a schema
|
||||
|
||||
REST framework supports either explicitly defined schema views, or
|
||||
automatically generated schemas. Since we're using viewsets and routers,
|
||||
we can simply use the automatic schema generation.
|
||||
|
||||
You'll need to install the `coreapi` python package in order to include an
|
||||
API schema, and `pyyaml` to render the schema into the commonly used
|
||||
YAML-based OpenAPI format.
|
||||
|
||||
$ pip install coreapi pyyaml
|
||||
|
||||
We can now include a schema for our API, by including an autogenerated schema
|
||||
view in our URL configuration.
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(title='Pastebin API')
|
||||
|
||||
urlpatterns = [
|
||||
path('schema/', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
If you visit the `/schema/` endpoint in a browser you should now see `corejson`
|
||||
representation become available as an option.
|
||||
|
||||

|
||||
|
||||
We can also request the schema from the command line, by specifying the desired
|
||||
content type in the `Accept` header.
|
||||
|
||||
$ http http://127.0.0.1:8000/schema/ Accept:application/coreapi+json
|
||||
HTTP/1.0 200 OK
|
||||
Allow: GET, HEAD, OPTIONS
|
||||
Content-Type: application/coreapi+json
|
||||
|
||||
{
|
||||
"_meta": {
|
||||
"title": "Pastebin API"
|
||||
},
|
||||
"_type": "document",
|
||||
...
|
||||
|
||||
The default output style is to use the [Core JSON][corejson] encoding.
|
||||
|
||||
Other schema formats, such as [Open API][openapi] (formerly Swagger) are
|
||||
also supported.
|
||||
|
||||
## Using a command line client
|
||||
|
||||
Now that our API is exposing a schema endpoint, we can use a dynamic client
|
||||
library to interact with the API. To demonstrate this, let's use the
|
||||
Core API command line client.
|
||||
|
||||
The command line client is available as the `coreapi-cli` package:
|
||||
|
||||
$ pip install coreapi-cli
|
||||
|
||||
Now check that it is available on the command line...
|
||||
|
||||
$ coreapi
|
||||
Usage: coreapi [OPTIONS] COMMAND [ARGS]...
|
||||
|
||||
Command line client for interacting with CoreAPI services.
|
||||
|
||||
Visit https://www.coreapi.org/ for more information.
|
||||
|
||||
Options:
|
||||
--version Display the package version number.
|
||||
--help Show this message and exit.
|
||||
|
||||
Commands:
|
||||
...
|
||||
|
||||
First we'll load the API schema using the command line client.
|
||||
|
||||
$ coreapi get http://127.0.0.1:8000/schema/
|
||||
<Pastebin API "http://127.0.0.1:8000/schema/">
|
||||
snippets: {
|
||||
highlight(id)
|
||||
list()
|
||||
read(id)
|
||||
}
|
||||
users: {
|
||||
list()
|
||||
read(id)
|
||||
}
|
||||
|
||||
We haven't authenticated yet, so right now we're only able to see the read only
|
||||
endpoints, in line with how we've set up the permissions on the API.
|
||||
|
||||
Let's try listing the existing snippets, using the command line client:
|
||||
|
||||
$ coreapi action snippets list
|
||||
[
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/snippets/1/",
|
||||
"id": 1,
|
||||
"highlight": "http://127.0.0.1:8000/snippets/1/highlight/",
|
||||
"owner": "lucy",
|
||||
"title": "Example",
|
||||
"code": "print('hello, world!')",
|
||||
"linenos": true,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
},
|
||||
...
|
||||
|
||||
Some of the API endpoints require named parameters. For example, to get back
|
||||
the highlight HTML for a particular snippet we need to provide an id.
|
||||
|
||||
$ coreapi action snippets highlight --param id=1
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>Example</title>
|
||||
...
|
||||
|
||||
## Authenticating our client
|
||||
|
||||
If we want to be able to create, edit and delete snippets, we'll need to
|
||||
authenticate as a valid user. In this case we'll just use basic auth.
|
||||
|
||||
Make sure to replace the `<username>` and `<password>` below with your
|
||||
actual username and password.
|
||||
|
||||
$ coreapi credentials add 127.0.0.1 <username>:<password> --auth basic
|
||||
Added credentials
|
||||
127.0.0.1 "Basic <...>"
|
||||
|
||||
Now if we fetch the schema again, we should be able to see the full
|
||||
set of available interactions.
|
||||
|
||||
$ coreapi reload
|
||||
Pastebin API "http://127.0.0.1:8000/schema/">
|
||||
snippets: {
|
||||
create(code, [title], [linenos], [language], [style])
|
||||
delete(id)
|
||||
highlight(id)
|
||||
list()
|
||||
partial_update(id, [title], [code], [linenos], [language], [style])
|
||||
read(id)
|
||||
update(id, code, [title], [linenos], [language], [style])
|
||||
}
|
||||
users: {
|
||||
list()
|
||||
read(id)
|
||||
}
|
||||
|
||||
We're now able to interact with these endpoints. For example, to create a new
|
||||
snippet:
|
||||
|
||||
$ coreapi action snippets create --param title="Example" --param code="print('hello, world')"
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/snippets/7/",
|
||||
"id": 7,
|
||||
"highlight": "http://127.0.0.1:8000/snippets/7/highlight/",
|
||||
"owner": "lucy",
|
||||
"title": "Example",
|
||||
"code": "print('hello, world')",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
|
||||
And to delete a snippet:
|
||||
|
||||
$ coreapi action snippets delete --param id=7
|
||||
|
||||
As well as the command line client, developers can also interact with your
|
||||
API using client libraries. The Python client library is the first of these
|
||||
to be available, and a Javascript client library is planned to be released
|
||||
soon.
|
||||
|
||||
For more details on customizing schema generation and using Core API
|
||||
client libraries you'll need to refer to the full documentation.
|
||||
|
||||
## Reviewing our work
|
||||
|
||||
With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats.
|
||||
|
||||
We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
|
||||
|
||||
You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
|
||||
|
||||
## Onwards and upwards
|
||||
|
||||
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:
|
||||
|
||||
* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
|
||||
* Join the [REST framework discussion group][group], and help build the community.
|
||||
* Follow [the author][twitter] on Twitter and say hi.
|
||||
|
||||
**Now go build awesome things.**
|
||||
|
||||
[coreapi]: https://www.coreapi.org/
|
||||
[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[openapi]: https://openapis.org/
|
||||
[repo]: https://github.com/encode/rest-framework-tutorial
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[github]: https://github.com/encode/django-rest-framework
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[twitter]: https://twitter.com/_tomchristie
|
|
@ -1,171 +0,0 @@
|
|||
|
||||
## Built-in API documentation
|
||||
|
||||
The built-in API documentation includes:
|
||||
|
||||
* Documentation of API endpoints.
|
||||
* Automatically generated code samples for each of the available API client libraries.
|
||||
* Support for API interaction.
|
||||
|
||||
### Installation
|
||||
|
||||
The `coreapi` library is required as a dependency for the API docs. Make sure
|
||||
to install the latest version. The `Pygments` and `Markdown` libraries
|
||||
are optional but recommended.
|
||||
|
||||
To install the API documentation, you'll need to include it in your project's URLconf:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
path('docs/', include_docs_urls(title='My API title'))
|
||||
]
|
||||
|
||||
This will include two different views:
|
||||
|
||||
* `/docs/` - The documentation page itself.
|
||||
* `/docs/schema.js` - A JavaScript resource that exposes the API schema.
|
||||
|
||||
---
|
||||
|
||||
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
||||
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
||||
|
||||
To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||
|
||||
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
# Generate schema with valid `request` instance:
|
||||
path('docs/', include_docs_urls(title='My API title', public=False))
|
||||
]
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Documenting your views
|
||||
|
||||
You can document your views by including docstrings that describe each of the available actions.
|
||||
For example:
|
||||
|
||||
class UserList(generics.ListAPIView):
|
||||
"""
|
||||
Return a list of all the existing users.
|
||||
"""
|
||||
|
||||
If a view supports multiple methods, you should split your documentation using `method:` style delimiters.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
"""
|
||||
get:
|
||||
Return a list of all the existing users.
|
||||
|
||||
post:
|
||||
Create a new user instance.
|
||||
"""
|
||||
|
||||
When using viewsets, you should use the relevant action names as delimiters.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
retrieve:
|
||||
Return the given user.
|
||||
|
||||
list:
|
||||
Return a list of all the existing users.
|
||||
|
||||
create:
|
||||
Create a new user instance.
|
||||
"""
|
||||
|
||||
Custom actions on viewsets can also be documented in a similar way using the method names
|
||||
as delimiters or by attaching the documentation to action mapping methods.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewset):
|
||||
...
|
||||
|
||||
@action(detail=False, methods=['get', 'post'])
|
||||
def some_action(self, request, *args, **kwargs):
|
||||
"""
|
||||
get:
|
||||
A description of the get method on the custom action.
|
||||
|
||||
post:
|
||||
A description of the post method on the custom action.
|
||||
"""
|
||||
|
||||
@some_action.mapping.put
|
||||
def put_some_action():
|
||||
"""
|
||||
A description of the put method on the custom action.
|
||||
"""
|
||||
|
||||
|
||||
### `documentation` API Reference
|
||||
|
||||
The `rest_framework.documentation` module provides three helper functions to help configure the interactive API documentation, `include_docs_urls` (usage shown above), `get_docs_view` and `get_schemajs_view`.
|
||||
|
||||
`include_docs_urls` employs `get_docs_view` and `get_schemajs_view` to generate the url patterns for the documentation page and JavaScript resource that exposes the API schema respectively. They expose the following options for customisation. (`get_docs_view` and `get_schemajs_view` ultimately call `rest_frameworks.schemas.get_schema_view()`, see the Schemas docs for more options there.)
|
||||
|
||||
#### `include_docs_urls`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. Should the schema be considered _public_? If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`.
|
||||
|
||||
#### `get_docs_view`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES`. May be used to pass custom permission classes to the `SchemaView`.
|
||||
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`. If `None` the `SchemaView` will be configured with `DocumentationRenderer` and `CoreJSONRenderer` renderers, corresponding to the (default) `html` and `corejson` formats.
|
||||
|
||||
#### `get_schemajs_view`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
|
||||
|
||||
### Customising code samples
|
||||
|
||||
The built-in API documentation includes automatically generated code samples for
|
||||
each of the available API client libraries.
|
||||
|
||||
You may customise these samples by subclassing `DocumentationRenderer`, setting
|
||||
`languages` to the list of languages you wish to support:
|
||||
|
||||
from rest_framework.renderers import DocumentationRenderer
|
||||
|
||||
|
||||
class CustomRenderer(DocumentationRenderer):
|
||||
languages = ['ruby', 'go']
|
||||
|
||||
For each language you need to provide an `intro` template, detailing installation instructions and such,
|
||||
plus a generic template for making API requests, that can be filled with individual request details.
|
||||
See the [templates for the bundled languages][client-library-templates] for examples.
|
||||
|
||||
---
|
||||
|
||||
[client-library-templates]: https://github.com/encode/django-rest-framework/tree/master/rest_framework/templates/rest_framework/docs/langs
|
|
@ -1,29 +0,0 @@
|
|||
# Legacy CoreAPI Schemas Docs
|
||||
|
||||
Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation in Django REST Framework v3.10.
|
||||
|
||||
See the [Version 3.10 Release Announcement](/community/3.10-announcement.md) for more details.
|
||||
|
||||
----
|
||||
|
||||
You can continue to use CoreAPI schemas by setting the appropriate default schema class:
|
||||
|
||||
```python
|
||||
# In settings.py
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
|
||||
}
|
||||
```
|
||||
|
||||
Under-the-hood, any subclass of `coreapi.AutoSchema` here will trigger use of the old CoreAPI schemas.
|
||||
**Otherwise** you will automatically be opted-in to the new OpenAPI schemas.
|
||||
|
||||
All CoreAPI related code will be removed in Django REST Framework v3.12. Switch to OpenAPI schemas by then.
|
||||
|
||||
----
|
||||
|
||||
For reference this folder contains the old CoreAPI related documentation:
|
||||
|
||||
* [Tutorial 7: Schemas & client libraries](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//7-schemas-and-client-libraries.md).
|
||||
* [Excerpts from _Documenting your API_ topic page](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//from-documenting-your-api.md).
|
||||
* [`rest_framework.schemas` API Reference](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//schemas.md).
|
|
@ -1,846 +0,0 @@
|
|||
source: schemas.py
|
||||
|
||||
# Schemas
|
||||
|
||||
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
|
||||
>
|
||||
> — Heroku, [JSON Schema for the Heroku Platform API][cite]
|
||||
|
||||
API schemas are a useful tool that allow for a range of use cases, including
|
||||
generating reference documentation, or driving dynamic client libraries that
|
||||
can interact with your API.
|
||||
|
||||
## Install Core API & PyYAML
|
||||
|
||||
You'll need to install the `coreapi` package in order to add schema support
|
||||
for REST framework. You probably also want to install `pyyaml`, so that you
|
||||
can render the schema into the commonly used YAML-based OpenAPI format.
|
||||
|
||||
pip install coreapi pyyaml
|
||||
|
||||
## Quickstart
|
||||
|
||||
There are two different ways you can serve a schema description for your API.
|
||||
|
||||
### Generating a schema with the `generateschema` management command
|
||||
|
||||
To generate a static API schema, use the `generateschema` management command.
|
||||
|
||||
```shell
|
||||
$ python manage.py generateschema > schema.yml
|
||||
```
|
||||
|
||||
Once you've generated a schema in this way you can annotate it with any
|
||||
additional information that cannot be automatically inferred by the schema
|
||||
generator.
|
||||
|
||||
You might want to check your API schema into version control and update it
|
||||
with each new release, or serve the API schema from your site's static media.
|
||||
|
||||
### Adding a view with `get_schema_view`
|
||||
|
||||
To add a dynamically generated schema view to your API, use `get_schema_view`.
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from django.urls import path
|
||||
|
||||
schema_view = get_schema_view(title="Example API")
|
||||
|
||||
urlpatterns = [
|
||||
path('schema', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
See below [for more details](#the-get_schema_view-shortcut) on customizing a
|
||||
dynamically generated schema view.
|
||||
|
||||
## Internal schema representation
|
||||
|
||||
REST framework uses [Core API][coreapi] in order to model schema information in
|
||||
a format-independent representation. This information can then be rendered
|
||||
into various different schema formats, or used to generate API documentation.
|
||||
|
||||
When using Core API, a schema is represented as a `Document` which is the
|
||||
top-level container object for information about the API. Available API
|
||||
interactions are represented using `Link` objects. Each link includes a URL,
|
||||
HTTP method, and may include a list of `Field` instances, which describe any
|
||||
parameters that may be accepted by the API endpoint. The `Link` and `Field`
|
||||
instances may also include descriptions, that allow an API schema to be
|
||||
rendered into user documentation.
|
||||
|
||||
Here's an example of an API description that includes a single `search`
|
||||
endpoint:
|
||||
|
||||
coreapi.Document(
|
||||
title='Flight Search API',
|
||||
url='https://api.example.org/',
|
||||
content={
|
||||
'search': coreapi.Link(
|
||||
url='/search/',
|
||||
action='get',
|
||||
fields=[
|
||||
coreapi.Field(
|
||||
name='from',
|
||||
required=True,
|
||||
location='query',
|
||||
description='City name or airport code.'
|
||||
),
|
||||
coreapi.Field(
|
||||
name='to',
|
||||
required=True,
|
||||
location='query',
|
||||
description='City name or airport code.'
|
||||
),
|
||||
coreapi.Field(
|
||||
name='date',
|
||||
required=True,
|
||||
location='query',
|
||||
description='Flight date in "YYYY-MM-DD" format.'
|
||||
)
|
||||
],
|
||||
description='Return flight availability and prices.'
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
## Schema output formats
|
||||
|
||||
In order to be presented in an HTTP response, the internal representation
|
||||
has to be rendered into the actual bytes that are used in the response.
|
||||
|
||||
REST framework includes a few different renderers that you can use for
|
||||
encoding the API schema.
|
||||
|
||||
* `renderers.OpenAPIRenderer` - Renders into YAML-based [OpenAPI][open-api], the most widely used API schema format.
|
||||
* `renderers.JSONOpenAPIRenderer` - Renders into JSON-based [OpenAPI][open-api].
|
||||
* `renderers.CoreJSONRenderer` - Renders into [Core JSON][corejson], a format designed for
|
||||
use with the `coreapi` client library.
|
||||
|
||||
|
||||
[Core JSON][corejson] is designed as a canonical format for use with Core API.
|
||||
REST framework includes a renderer class for handling this media type, which
|
||||
is available as `renderers.CoreJSONRenderer`.
|
||||
|
||||
|
||||
## Schemas vs Hypermedia
|
||||
|
||||
It's worth pointing out here that Core API can also be used to model hypermedia
|
||||
responses, which present an alternative interaction style to API schemas.
|
||||
|
||||
With an API schema, the entire available interface is presented up-front
|
||||
as a single endpoint. Responses to individual API endpoints are then typically
|
||||
presented as plain data, without any further interactions contained in each
|
||||
response.
|
||||
|
||||
With Hypermedia, the client is instead presented with a document containing
|
||||
both data and available interactions. Each interaction results in a new
|
||||
document, detailing both the current state and the available interactions.
|
||||
|
||||
Further information and support on building Hypermedia APIs with REST framework
|
||||
is planned for a future version.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Creating a schema
|
||||
|
||||
REST framework includes functionality for auto-generating a schema,
|
||||
or allows you to specify one explicitly.
|
||||
|
||||
## Manual Schema Specification
|
||||
|
||||
To manually specify a schema you create a Core API `Document`, similar to the
|
||||
example above.
|
||||
|
||||
schema = coreapi.Document(
|
||||
title='Flight Search API',
|
||||
content={
|
||||
...
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
## Automatic Schema Generation
|
||||
|
||||
Automatic schema generation is provided by the `SchemaGenerator` class.
|
||||
|
||||
`SchemaGenerator` processes a list of routed URL patterns and compiles the
|
||||
appropriately structured Core API Document.
|
||||
|
||||
Basic usage is just to provide the title for your schema and call
|
||||
`get_schema()`:
|
||||
|
||||
generator = schemas.SchemaGenerator(title='Flight Search API')
|
||||
schema = generator.get_schema()
|
||||
|
||||
## Per-View Schema Customisation
|
||||
|
||||
By default, view introspection is performed by an `AutoSchema` instance
|
||||
accessible via the `schema` attribute on `APIView`. This provides the
|
||||
appropriate Core API `Link` object for the view, request method and path:
|
||||
|
||||
auto_schema = view.schema
|
||||
coreapi_link = auto_schema.get_link(...)
|
||||
|
||||
(In compiling the schema, `SchemaGenerator` calls `view.schema.get_link()` for
|
||||
each view, allowed method and path.)
|
||||
|
||||
---
|
||||
|
||||
**Note**: For basic `APIView` subclasses, default introspection is essentially
|
||||
limited to the URL kwarg path parameters. For `GenericAPIView`
|
||||
subclasses, which includes all the provided class based views, `AutoSchema` will
|
||||
attempt to introspect serializer, pagination and filter fields, as well as
|
||||
provide richer path field descriptions. (The key hooks here are the relevant
|
||||
`GenericAPIView` attributes and methods: `get_serializer`, `pagination_class`,
|
||||
`filter_backends` and so on.)
|
||||
|
||||
---
|
||||
|
||||
To customise the `Link` generation you may:
|
||||
|
||||
* Instantiate `AutoSchema` on your view with the `manual_fields` kwarg:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = AutoSchema(
|
||||
manual_fields=[
|
||||
coreapi.Field("extra_field", ...),
|
||||
]
|
||||
)
|
||||
|
||||
This allows extension for the most common case without subclassing.
|
||||
|
||||
* Provide an `AutoSchema` subclass with more complex customisation:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomSchema(AutoSchema):
|
||||
def get_link(...):
|
||||
# Implement custom introspection here (or in other sub-methods)
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = CustomSchema()
|
||||
|
||||
This provides complete control over view introspection.
|
||||
|
||||
* Instantiate `ManualSchema` on your view, providing the Core API `Fields` for
|
||||
the view explicitly:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import ManualSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = ManualSchema(fields=[
|
||||
coreapi.Field(
|
||||
"first_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
coreapi.Field(
|
||||
"second_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
])
|
||||
|
||||
This allows manually specifying the schema for some views whilst maintaining
|
||||
automatic generation elsewhere.
|
||||
|
||||
You may disable schema generation for a view by setting `schema` to `None`:
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = None # Will not appear in schema
|
||||
|
||||
This also applies to extra actions for `ViewSet`s:
|
||||
|
||||
class CustomViewSet(viewsets.ModelViewSet):
|
||||
|
||||
@action(detail=True, schema=None)
|
||||
def extra_action(self, request, pk=None):
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
**Note**: For full details on `SchemaGenerator` plus the `AutoSchema` and
|
||||
`ManualSchema` descriptors see the [API Reference below](#api-reference).
|
||||
|
||||
---
|
||||
|
||||
# Adding a schema view
|
||||
|
||||
There are a few different ways to add a schema view to your API, depending on
|
||||
exactly what you need.
|
||||
|
||||
## The get_schema_view shortcut
|
||||
|
||||
The simplest way to include a schema in your project is to use the
|
||||
`get_schema_view()` function.
|
||||
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(title="Server Monitoring API")
|
||||
|
||||
urlpatterns = [
|
||||
path('', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
Once the view has been added, you'll be able to make API requests to retrieve
|
||||
the auto-generated schema definition.
|
||||
|
||||
$ http http://127.0.0.1:8000/ Accept:application/coreapi+json
|
||||
HTTP/1.0 200 OK
|
||||
Allow: GET, HEAD, OPTIONS
|
||||
Content-Type: application/vnd.coreapi+json
|
||||
|
||||
{
|
||||
"_meta": {
|
||||
"title": "Server Monitoring API"
|
||||
},
|
||||
"_type": "document",
|
||||
...
|
||||
}
|
||||
|
||||
The arguments to `get_schema_view()` are:
|
||||
|
||||
#### `title`
|
||||
|
||||
May be used to provide a descriptive title for the schema definition.
|
||||
|
||||
#### `url`
|
||||
|
||||
May be used to pass a canonical URL for the schema.
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/'
|
||||
)
|
||||
|
||||
#### `urlconf`
|
||||
|
||||
A string representing the import path to the URL conf that you want
|
||||
to generate an API schema for. This defaults to the value of Django's
|
||||
ROOT_URLCONF setting.
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
urlconf='myproject.urls'
|
||||
)
|
||||
|
||||
#### `renderer_classes`
|
||||
|
||||
May be used to pass the set of renderer classes that can be used to render the API root endpoint.
|
||||
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.renderers import JSONOpenAPIRenderer
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
renderer_classes=[JSONOpenAPIRenderer]
|
||||
)
|
||||
|
||||
#### `patterns`
|
||||
|
||||
List of url patterns to limit the schema introspection to. If you only want the `myproject.api` urls
|
||||
to be exposed in the schema:
|
||||
|
||||
schema_url_patterns = [
|
||||
path('api/', include('myproject.api.urls')),
|
||||
]
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
patterns=schema_url_patterns,
|
||||
)
|
||||
|
||||
#### `generator_class`
|
||||
|
||||
May be used to specify a `SchemaGenerator` subclass to be passed to the
|
||||
`SchemaView`.
|
||||
|
||||
#### `authentication_classes`
|
||||
|
||||
May be used to specify the list of authentication classes that will apply to the schema endpoint.
|
||||
Defaults to `settings.DEFAULT_AUTHENTICATION_CLASSES`
|
||||
|
||||
#### `permission_classes`
|
||||
|
||||
May be used to specify the list of permission classes that will apply to the schema endpoint.
|
||||
Defaults to `settings.DEFAULT_PERMISSION_CLASSES`
|
||||
|
||||
## Using an explicit schema view
|
||||
|
||||
If you need a little more control than the `get_schema_view()` shortcut gives you,
|
||||
then you can use the `SchemaGenerator` class directly to auto-generate the
|
||||
`Document` instance, and to return that from a view.
|
||||
|
||||
This option gives you the flexibility of setting up the schema endpoint
|
||||
with whatever behaviour you want. For example, you can apply different
|
||||
permission, throttling, or authentication policies to the schema endpoint.
|
||||
|
||||
Here's an example of using `SchemaGenerator` together with a view to
|
||||
return the schema.
|
||||
|
||||
**views.py:**
|
||||
|
||||
from rest_framework.decorators import api_view, renderer_classes
|
||||
from rest_framework import renderers, response, schemas
|
||||
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
schema = generator.get_schema(request)
|
||||
return response.Response(schema)
|
||||
|
||||
**urls.py:**
|
||||
|
||||
urlpatterns = [
|
||||
path('', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
You can also serve different schemas to different users, depending on the
|
||||
permissions they have available. This approach can be used to ensure that
|
||||
unauthenticated requests are presented with a different schema to
|
||||
authenticated requests, or to ensure that different parts of the API are
|
||||
made visible to different users depending on their role.
|
||||
|
||||
In order to present a schema with endpoints filtered by user permissions,
|
||||
you need to pass the `request` argument to the `get_schema()` method, like so:
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
return response.Response(generator.get_schema(request=request))
|
||||
|
||||
## Explicit schema definition
|
||||
|
||||
An alternative to the auto-generated approach is to specify the API schema
|
||||
explicitly, by declaring a `Document` object in your codebase. Doing so is a
|
||||
little more work, but ensures that you have full control over the schema
|
||||
representation.
|
||||
|
||||
import coreapi
|
||||
from rest_framework.decorators import api_view, renderer_classes
|
||||
from rest_framework import renderers, response
|
||||
|
||||
schema = coreapi.Document(
|
||||
title='Bookings API',
|
||||
content={
|
||||
...
|
||||
}
|
||||
)
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
return response.Response(schema)
|
||||
|
||||
---
|
||||
|
||||
# Schemas as documentation
|
||||
|
||||
One common usage of API schemas is to use them to build documentation pages.
|
||||
|
||||
The schema generation in REST framework uses docstrings to automatically
|
||||
populate descriptions in the schema document.
|
||||
|
||||
These descriptions will be based on:
|
||||
|
||||
* The corresponding method docstring if one exists.
|
||||
* A named section within the class docstring, which can be either single line or multi-line.
|
||||
* The class docstring.
|
||||
|
||||
## Examples
|
||||
|
||||
An `APIView`, with an explicit method docstring.
|
||||
|
||||
class ListUsernames(APIView):
|
||||
def get(self, request):
|
||||
"""
|
||||
Return a list of all user names in the system.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
A `ViewSet`, with an explicit action docstring.
|
||||
|
||||
class ListUsernames(ViewSet):
|
||||
def list(self, request):
|
||||
"""
|
||||
Return a list of all user names in the system.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
A generic view with sections in the class docstring, using single-line style.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
"""
|
||||
get: List all the users.
|
||||
post: Create a new user.
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = [IsAdminUser]
|
||||
|
||||
A generic viewset with sections in the class docstring, using multi-line style.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
API endpoint that allows users to be viewed or edited.
|
||||
|
||||
retrieve:
|
||||
Return a user instance.
|
||||
|
||||
list:
|
||||
Return all users, ordered by most recently joined.
|
||||
"""
|
||||
queryset = User.objects.all().order_by('-date_joined')
|
||||
serializer_class = UserSerializer
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## SchemaGenerator
|
||||
|
||||
A class that walks a list of routed URL patterns, requests the schema for each view,
|
||||
and collates the resulting CoreAPI Document.
|
||||
|
||||
Typically you'll instantiate `SchemaGenerator` with a single argument, like so:
|
||||
|
||||
generator = SchemaGenerator(title='Stock Prices API')
|
||||
|
||||
Arguments:
|
||||
|
||||
* `title` **required** - The name of the API.
|
||||
* `url` - The root URL of the API schema. This option is not required unless the schema is included under path prefix.
|
||||
* `patterns` - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
|
||||
* `urlconf` - A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`.
|
||||
|
||||
### get_schema(self, request)
|
||||
|
||||
Returns a `coreapi.Document` instance that represents the API schema.
|
||||
|
||||
@api_view
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
return Response(generator.get_schema())
|
||||
|
||||
The `request` argument is optional, and may be used if you want to apply per-user
|
||||
permissions to the resulting schema generation.
|
||||
|
||||
### get_links(self, request)
|
||||
|
||||
Return a nested dictionary containing all the links that should be included in the API schema.
|
||||
|
||||
This is a good point to override if you want to modify the resulting structure of the generated schema,
|
||||
as you can build a new dictionary with a different layout.
|
||||
|
||||
|
||||
## AutoSchema
|
||||
|
||||
A class that deals with introspection of individual views for schema generation.
|
||||
|
||||
`AutoSchema` is attached to `APIView` via the `schema` attribute.
|
||||
|
||||
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
|
||||
|
||||
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
|
||||
the generated fields. Generated fields with a matching `name` will be overwritten.
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = AutoSchema(manual_fields=[
|
||||
coreapi.Field(
|
||||
"my_extra_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
])
|
||||
|
||||
For more advanced customisation subclass `AutoSchema` to customise schema generation.
|
||||
|
||||
class CustomViewSchema(AutoSchema):
|
||||
"""
|
||||
Overrides `get_link()` to provide Custom Behavior X
|
||||
"""
|
||||
|
||||
def get_link(self, path, method, base_url):
|
||||
link = super().get_link(path, method, base_url)
|
||||
# Do something to customize link here...
|
||||
return link
|
||||
|
||||
class MyView(APIView):
|
||||
schema = CustomViewSchema()
|
||||
|
||||
The following methods are available to override.
|
||||
|
||||
### get_link(self, path, method, base_url)
|
||||
|
||||
Returns a `coreapi.Link` instance corresponding to the given view.
|
||||
|
||||
This is the main entry point.
|
||||
You can override this if you need to provide custom behaviors for particular views.
|
||||
|
||||
### get_description(self, path, method)
|
||||
|
||||
Returns a string to use as the link description. By default this is based on the
|
||||
view docstring as described in the "Schemas as Documentation" section above.
|
||||
|
||||
### get_encoding(self, path, method)
|
||||
|
||||
Returns a string to indicate the encoding for any request body, when interacting
|
||||
with the given view. Eg. `'application/json'`. May return a blank string for views
|
||||
that do not expect a request body.
|
||||
|
||||
### get_path_fields(self, path, method):
|
||||
|
||||
Return a list of `coreapi.Field()` instances. One for each path parameter in the URL.
|
||||
|
||||
### get_serializer_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances. One for each field in the serializer class used by the view.
|
||||
|
||||
### get_pagination_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view.
|
||||
|
||||
### get_filter_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view.
|
||||
|
||||
### get_manual_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances to be added to or replace generated fields. Defaults to (optional) `manual_fields` passed to `AutoSchema` constructor.
|
||||
|
||||
May be overridden to customise manual fields by `path` or `method`. For example, a per-method adjustment may look like this:
|
||||
|
||||
```python
|
||||
def get_manual_fields(self, path, method):
|
||||
"""Example adding per-method fields."""
|
||||
|
||||
extra_fields = []
|
||||
if method=='GET':
|
||||
extra_fields = # ... list of extra fields for GET ...
|
||||
if method=='POST':
|
||||
extra_fields = # ... list of extra fields for POST ...
|
||||
|
||||
manual_fields = super().get_manual_fields(path, method)
|
||||
return manual_fields + extra_fields
|
||||
```
|
||||
|
||||
### update_fields(fields, update_with)
|
||||
|
||||
Utility `staticmethod`. Encapsulates logic to add or replace fields from a list
|
||||
by `Field.name`. May be overridden to adjust replacement criteria.
|
||||
|
||||
|
||||
## ManualSchema
|
||||
|
||||
Allows manually providing a list of `coreapi.Field` instances for the schema,
|
||||
plus an optional description.
|
||||
|
||||
class MyView(APIView):
|
||||
schema = ManualSchema(fields=[
|
||||
coreapi.Field(
|
||||
"first_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
coreapi.Field(
|
||||
"second_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
The `ManualSchema` constructor takes two arguments:
|
||||
|
||||
**`fields`**: A list of `coreapi.Field` instances. Required.
|
||||
|
||||
**`description`**: A string description. Optional.
|
||||
|
||||
**`encoding`**: Default `None`. A string encoding, e.g `application/json`. Optional.
|
||||
|
||||
---
|
||||
|
||||
## Core API
|
||||
|
||||
This documentation gives a brief overview of the components within the `coreapi`
|
||||
package that are used to represent an API schema.
|
||||
|
||||
Note that these classes are imported from the `coreapi` package, rather than
|
||||
from the `rest_framework` package.
|
||||
|
||||
### Document
|
||||
|
||||
Represents a container for the API schema.
|
||||
|
||||
#### `title`
|
||||
|
||||
A name for the API.
|
||||
|
||||
#### `url`
|
||||
|
||||
A canonical URL for the API.
|
||||
|
||||
#### `content`
|
||||
|
||||
A dictionary, containing the `Link` objects that the schema contains.
|
||||
|
||||
In order to provide more structure to the schema, the `content` dictionary
|
||||
may be nested, typically to a second level. For example:
|
||||
|
||||
content={
|
||||
"bookings": {
|
||||
"list": Link(...),
|
||||
"create": Link(...),
|
||||
...
|
||||
},
|
||||
"venues": {
|
||||
"list": Link(...),
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
### Link
|
||||
|
||||
Represents an individual API endpoint.
|
||||
|
||||
#### `url`
|
||||
|
||||
The URL of the endpoint. May be a URI template, such as `/users/{username}/`.
|
||||
|
||||
#### `action`
|
||||
|
||||
The HTTP method associated with the endpoint. Note that URLs that support
|
||||
more than one HTTP method, should correspond to a single `Link` for each.
|
||||
|
||||
#### `fields`
|
||||
|
||||
A list of `Field` instances, describing the available parameters on the input.
|
||||
|
||||
#### `description`
|
||||
|
||||
A short description of the meaning and intended usage of the endpoint.
|
||||
|
||||
### Field
|
||||
|
||||
Represents a single input parameter on a given API endpoint.
|
||||
|
||||
#### `name`
|
||||
|
||||
A descriptive name for the input.
|
||||
|
||||
#### `required`
|
||||
|
||||
A boolean, indicated if the client is required to included a value, or if
|
||||
the parameter can be omitted.
|
||||
|
||||
#### `location`
|
||||
|
||||
Determines how the information is encoded into the request. Should be one of
|
||||
the following strings:
|
||||
|
||||
**"path"**
|
||||
|
||||
Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`.
|
||||
|
||||
These fields will normally correspond with [named arguments in the project URL conf][named-arguments].
|
||||
|
||||
**"query"**
|
||||
|
||||
Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests.
|
||||
|
||||
These fields will normally correspond with pagination and filtering controls on a view.
|
||||
|
||||
**"form"**
|
||||
|
||||
Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link.
|
||||
|
||||
These fields will normally correspond with serializer fields on a view.
|
||||
|
||||
**"body"**
|
||||
|
||||
Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields.
|
||||
|
||||
These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views.
|
||||
|
||||
#### `encoding`
|
||||
|
||||
**"application/json"**
|
||||
|
||||
JSON encoded request content. Corresponds to views using `JSONParser`.
|
||||
Valid only if either one or more `location="form"` fields, or a single
|
||||
`location="body"` field is included on the `Link`.
|
||||
|
||||
**"multipart/form-data"**
|
||||
|
||||
Multipart encoded request content. Corresponds to views using `MultiPartParser`.
|
||||
Valid only if one or more `location="form"` fields is included on the `Link`.
|
||||
|
||||
**"application/x-www-form-urlencoded"**
|
||||
|
||||
URL encoded request content. Corresponds to views using `FormParser`. Valid
|
||||
only if one or more `location="form"` fields is included on the `Link`.
|
||||
|
||||
**"application/octet-stream"**
|
||||
|
||||
Binary upload request content. Corresponds to views using `FileUploadParser`.
|
||||
Valid only if a `location="body"` field is included on the `Link`.
|
||||
|
||||
#### `description`
|
||||
|
||||
A short description of the meaning and intended usage of the input field.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
## drf-yasg - Yet Another Swagger Generator
|
||||
|
||||
[drf-yasg][drf-yasg] generates [OpenAPI][open-api] documents suitable for code generation - nested schemas,
|
||||
named models, response bodies, enum/pattern/min/max validators, form parameters, etc.
|
||||
|
||||
|
||||
## drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework
|
||||
|
||||
[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility,
|
||||
customizability and client generation. It's usage patterns are very similar to [drf-yasg][drf-yasg].
|
||||
|
||||
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
|
||||
[coreapi]: https://www.coreapi.org/
|
||||
[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[drf-yasg]: https://github.com/axnsan12/drf-yasg/
|
||||
[drf-spectacular]: https://github.com/tfranzel/drf-spectacular/
|
||||
[open-api]: https://openapis.org/
|
||||
[json-hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html
|
||||
[api-blueprint]: https://apiblueprint.org/
|
||||
[static-files]: https://docs.djangoproject.com/en/stable/howto/static-files/
|
||||
[named-arguments]: https://docs.djangoproject.com/en/stable/topics/http/urls/#named-groups
|
BIN
docs/img/books/dfa-40-cover.jpg
Normal file
After Width: | Height: | Size: 755 KiB |
BIN
docs/img/build-status.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
docs/img/drf-m-api-root.png
Normal file
After Width: | Height: | Size: 81 KiB |
BIN
docs/img/drf-m-detail-view.png
Normal file
After Width: | Height: | Size: 121 KiB |
BIN
docs/img/drf-m-list-view.png
Normal file
After Width: | Height: | Size: 123 KiB |
BIN
docs/img/drf-r-api-root.png
Normal file
After Width: | Height: | Size: 82 KiB |
BIN
docs/img/drf-r-detail-view.png
Normal file
After Width: | Height: | Size: 118 KiB |
BIN
docs/img/drf-r-list-view.png
Normal file
After Width: | Height: | Size: 127 KiB |
BIN
docs/img/drf-rw-api-root.png
Normal file
After Width: | Height: | Size: 76 KiB |
BIN
docs/img/drf-rw-detail-view.png
Normal file
After Width: | Height: | Size: 99 KiB |
BIN
docs/img/drf-rw-list-view.png
Normal file
After Width: | Height: | Size: 100 KiB |
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
BIN
docs/img/premium/cryptapi-readme.png
Normal file
After Width: | Height: | Size: 17 KiB |
BIN
docs/img/premium/fezto-readme.png
Normal file
After Width: | Height: | Size: 22 KiB |
BIN
docs/img/premium/posthog-readme.png
Normal file
After Width: | Height: | Size: 4.8 KiB |
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 8.7 KiB |
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
BIN
docs/img/premium/spacinov-readme.png
Normal file
After Width: | Height: | Size: 56 KiB |
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
BIN
docs/img/premium/svix-premium.png
Normal file
After Width: | Height: | Size: 31 KiB |
BIN
docs/img/premium/zuplo-readme.png
Normal file
After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 27 KiB |
Before Width: | Height: | Size: 9.8 KiB |
|
@ -20,8 +20,8 @@
|
|||
<p class="badges" height=20px>
|
||||
<iframe src="https://ghbtns.com/github-btn.html?user=encode&repo=django-rest-framework&type=watch&count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
|
||||
|
||||
<a href="https://travis-ci.org/encode/django-rest-framework?branch=master">
|
||||
<img src="https://secure.travis-ci.org/encode/django-rest-framework.svg?branch=master" class="status-badge">
|
||||
<a href="https://github.com/encode/django-rest-framework/actions/workflows/main.yml">
|
||||
<img src="https://github.com/encode/django-rest-framework/actions/workflows/main.yml/badge.svg" class="status-badge">
|
||||
</a>
|
||||
|
||||
<a href="https://pypi.org/project/djangorestframework/">
|
||||
|
@ -48,7 +48,7 @@ Django REST framework is a powerful and flexible toolkit for building Web APIs.
|
|||
|
||||
Some reasons you might want to use REST framework:
|
||||
|
||||
* The [Web browsable API][sandbox] is a huge usability win for your developers.
|
||||
* The Web browsable API is a huge usability win for your developers.
|
||||
* [Authentication policies][authentication] including packages for [OAuth1a][oauth1-section] and [OAuth2][oauth2-section].
|
||||
* [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources.
|
||||
* Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers].
|
||||
|
@ -67,15 +67,19 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
|
||||
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
|
||||
<li><a href="https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://www.spacinov.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/spacinov.png)">Spacinov</a></li>
|
||||
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
|
||||
<li><a href="https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/bitio_logo_gold_background.png)">bit.io</a></li>
|
||||
<li><a href="https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/135996800-d49fe024-32d9-441a-98d9-4c7596287a67.png)">PostHog</a></li>
|
||||
<li><a href="https://cryptapi.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cryptapi.png)">CryptAPI</a></li>
|
||||
<li><a href="https://www.fezto.xyz/?utm_source=DjangoRESTFramework" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/fezto.png)">FEZTO</a></li>
|
||||
<li><a href="https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/svix.png)">Svix</a></li>
|
||||
<li><a href="https://zuplo.link/django-web" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/zuplo.png)">Zuplo</a></li>
|
||||
</ul>
|
||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||
|
||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), and [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship).*
|
||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [Spacinov](https://www.spacinov.com/), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [CryptAPI](https://cryptapi.io), [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework), [Svix](https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship), , and [Zuplo](https://zuplo.link/django-web).*
|
||||
|
||||
---
|
||||
|
||||
|
@ -83,8 +87,8 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
REST framework requires the following:
|
||||
|
||||
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
|
||||
* Django (2.2, 3.0, 3.1)
|
||||
* Django (4.2, 5.0, 5.1, 5.2)
|
||||
* Python (3.9, 3.10, 3.11, 3.12, 3.13)
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
@ -92,8 +96,8 @@ each Python and Django series.
|
|||
The following packages are optional:
|
||||
|
||||
* [PyYAML][pyyaml], [uritemplate][uriteemplate] (5.1+, 3.0.0+) - Schema generation support.
|
||||
* [Markdown][markdown] (3.0.0+) - Markdown support for the browsable API.
|
||||
* [Pygments][pygments] (2.4.0+) - Add syntax highlighting to Markdown processing.
|
||||
* [Markdown][markdown] (3.3.0+) - Markdown support for the browsable API.
|
||||
* [Pygments][pygments] (2.7.0+) - Add syntax highlighting to Markdown processing.
|
||||
* [django-filter][django-filter] (1.0.1+) - Filtering support.
|
||||
* [django-guardian][django-guardian] (1.1.1+) - Object level permissions support.
|
||||
|
||||
|
@ -181,20 +185,20 @@ Can't wait to get started? The [quickstart guide][quickstart] is the fastest way
|
|||
## Development
|
||||
|
||||
See the [Contribution guidelines][contributing] for information on how to clone
|
||||
the repository, run the test suite and contribute changes back to REST
|
||||
the repository, run the test suite and help maintain the code base of REST
|
||||
Framework.
|
||||
|
||||
## Support
|
||||
|
||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, search [the IRC archives][botbot], or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||
|
||||
For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/).
|
||||
|
||||
## Security
|
||||
|
||||
If you believe you’ve found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
**Please report security issues by emailing security@encode.io**.
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
||||
## License
|
||||
|
||||
|
@ -242,7 +246,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[serializer-section]: api-guide/serializers#serializers
|
||||
[modelserializer-section]: api-guide/serializers#modelserializer
|
||||
[functionview-section]: api-guide/views#function-based-views
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
|
||||
[quickstart]: tutorial/quickstart.md
|
||||
|
@ -257,7 +260,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[funding]: community/funding.md
|
||||
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[botbot]: https://botbot.me/freenode/restframework/
|
||||
[stack-overflow]: https://stackoverflow.com/
|
||||
[django-rest-framework-tag]: https://stackoverflow.com/questions/tagged/django-rest-framework
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
|
||||
>
|
||||
> — [Jeff Atwood][cite]
|
||||
> — [Jeff Atwood][cite]
|
||||
|
||||
## Javascript clients
|
||||
|
||||
|
@ -31,11 +31,11 @@ In order to make AJAX requests, you need to include CSRF token in the HTTP heade
|
|||
|
||||
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
|
||||
|
||||
[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
[Adam Johnson][adamchainz] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
|
||||
[cite]: https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
|
||||
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax
|
||||
[cors]: https://www.w3.org/TR/cors/
|
||||
[ottoyiu]: https://github.com/ottoyiu/
|
||||
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
|
||||
[adamchainz]: https://github.com/adamchainz
|
||||
[django-cors-headers]: https://github.com/adamchainz/django-cors-headers
|
||||
|
|
|
@ -1,527 +0,0 @@
|
|||
# API Clients
|
||||
|
||||
An API client handles the underlying details of how network requests are made
|
||||
and how responses are decoded. They present the developer with an application
|
||||
interface to work against, rather than working directly with the network interface.
|
||||
|
||||
The API clients documented here are not restricted to APIs built with Django REST framework.
|
||||
They can be used with any API that exposes a supported schema format.
|
||||
|
||||
For example, [the Heroku platform API][heroku-api] exposes a schema in the JSON
|
||||
Hyperschema format. As a result, the Core API command line client and Python
|
||||
client library can be [used to interact with the Heroku API][heroku-example].
|
||||
|
||||
## Client-side Core API
|
||||
|
||||
[Core API][core-api] is a document specification that can be used to describe APIs. It can
|
||||
be used either server-side, as is done with REST framework's [schema generation][schema-generation],
|
||||
or used client-side, as described here.
|
||||
|
||||
When used client-side, Core API allows for *dynamically driven client libraries*
|
||||
that can interact with any API that exposes a supported schema or hypermedia
|
||||
format.
|
||||
|
||||
Using a dynamically driven client has a number of advantages over interacting
|
||||
with an API by building HTTP requests directly.
|
||||
|
||||
#### More meaningful interaction
|
||||
|
||||
API interactions are presented in a more meaningful way. You're working at
|
||||
the application interface layer, rather than the network interface layer.
|
||||
|
||||
#### Resilience & evolvability
|
||||
|
||||
The client determines what endpoints are available, what parameters exist
|
||||
against each particular endpoint, and how HTTP requests are formed.
|
||||
|
||||
This also allows for a degree of API evolvability. URLs can be modified
|
||||
without breaking existing clients, or more efficient encodings can be used
|
||||
on-the-wire, with clients transparently upgrading.
|
||||
|
||||
#### Self-descriptive APIs
|
||||
|
||||
A dynamically driven client is able to present documentation on the API to the
|
||||
end user. This documentation allows the user to discover the available endpoints
|
||||
and parameters, and better understand the API they are working with.
|
||||
|
||||
Because this documentation is driven by the API schema it will always be fully
|
||||
up to date with the most recently deployed version of the service.
|
||||
|
||||
---
|
||||
|
||||
# Command line client
|
||||
|
||||
The command line client allows you to inspect and interact with any API that
|
||||
exposes a supported schema format.
|
||||
|
||||
## Getting started
|
||||
|
||||
To install the Core API command line client, use `pip`.
|
||||
|
||||
Note that the command-line client is a separate package to the
|
||||
python client library. Make sure to install `coreapi-cli`.
|
||||
|
||||
$ pip install coreapi-cli
|
||||
|
||||
To start inspecting and interacting with an API the schema must first be loaded
|
||||
from the network.
|
||||
|
||||
$ coreapi get http://api.example.org/
|
||||
<Pastebin API "http://127.0.0.1:8000/">
|
||||
snippets: {
|
||||
create(code, [title], [linenos], [language], [style])
|
||||
destroy(pk)
|
||||
highlight(pk)
|
||||
list([page])
|
||||
partial_update(pk, [title], [code], [linenos], [language], [style])
|
||||
retrieve(pk)
|
||||
update(pk, code, [title], [linenos], [language], [style])
|
||||
}
|
||||
users: {
|
||||
list([page])
|
||||
retrieve(pk)
|
||||
}
|
||||
|
||||
This will then load the schema, displaying the resulting `Document`. This
|
||||
`Document` includes all the available interactions that may be made against the API.
|
||||
|
||||
To interact with the API, use the `action` command. This command requires a list
|
||||
of keys that are used to index into the link.
|
||||
|
||||
$ coreapi action users list
|
||||
[
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/users/2/",
|
||||
"id": 2,
|
||||
"username": "aziz",
|
||||
"snippets": []
|
||||
},
|
||||
...
|
||||
]
|
||||
|
||||
To inspect the underlying HTTP request and response, use the `--debug` flag.
|
||||
|
||||
$ coreapi action users list --debug
|
||||
> GET /users/ HTTP/1.1
|
||||
> Accept: application/vnd.coreapi+json, */*
|
||||
> Authorization: Basic bWF4Om1heA==
|
||||
> Host: 127.0.0.1
|
||||
> User-Agent: coreapi
|
||||
< 200 OK
|
||||
< Allow: GET, HEAD, OPTIONS
|
||||
< Content-Type: application/json
|
||||
< Date: Thu, 30 Jun 2016 10:51:46 GMT
|
||||
< Server: WSGIServer/0.1 Python/2.7.10
|
||||
< Vary: Accept, Cookie
|
||||
<
|
||||
< [{"url":"http://127.0.0.1/users/2/","id":2,"username":"aziz","snippets":[]},{"url":"http://127.0.0.1/users/3/","id":3,"username":"amy","snippets":["http://127.0.0.1/snippets/3/"]},{"url":"http://127.0.0.1/users/4/","id":4,"username":"max","snippets":["http://127.0.0.1/snippets/4/","http://127.0.0.1/snippets/5/","http://127.0.0.1/snippets/6/","http://127.0.0.1/snippets/7/"]},{"url":"http://127.0.0.1/users/5/","id":5,"username":"jose","snippets":[]},{"url":"http://127.0.0.1/users/6/","id":6,"username":"admin","snippets":["http://127.0.0.1/snippets/1/","http://127.0.0.1/snippets/2/"]}]
|
||||
|
||||
[
|
||||
...
|
||||
]
|
||||
|
||||
Some actions may include optional or required parameters.
|
||||
|
||||
$ coreapi action users create --param username=example
|
||||
|
||||
When using `--param`, the type of the input will be determined automatically.
|
||||
|
||||
If you want to be more explicit about the parameter type then use `--data` for
|
||||
any null, numeric, boolean, list, or object inputs, and use `--string` for string inputs.
|
||||
|
||||
$ coreapi action users edit --string username=tomchristie --data is_admin=true
|
||||
|
||||
## Authentication & headers
|
||||
|
||||
The `credentials` command is used to manage the request `Authentication:` header.
|
||||
Any credentials added are always linked to a particular domain, so as to ensure
|
||||
that credentials are not leaked across differing APIs.
|
||||
|
||||
The format for adding a new credential is:
|
||||
|
||||
$ coreapi credentials add <domain> <credentials string>
|
||||
|
||||
For instance:
|
||||
|
||||
$ coreapi credentials add api.example.org "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"
|
||||
|
||||
The optional `--auth` flag also allows you to add specific types of authentication,
|
||||
handling the encoding for you. Currently only `"basic"` is supported as an option here.
|
||||
For example:
|
||||
|
||||
$ coreapi credentials add api.example.org tomchristie:foobar --auth basic
|
||||
|
||||
You can also add specific request headers, using the `headers` command:
|
||||
|
||||
$ coreapi headers add api.example.org x-api-version 2
|
||||
|
||||
For more information and a listing of the available subcommands use `coreapi
|
||||
credentials --help` or `coreapi headers --help`.
|
||||
|
||||
## Codecs
|
||||
|
||||
By default the command line client only includes support for reading Core JSON
|
||||
schemas, however it includes a plugin system for installing additional codecs.
|
||||
|
||||
$ pip install openapi-codec jsonhyperschema-codec hal-codec
|
||||
$ coreapi codecs show
|
||||
Codecs
|
||||
corejson application/vnd.coreapi+json encoding, decoding
|
||||
hal application/hal+json encoding, decoding
|
||||
openapi application/openapi+json encoding, decoding
|
||||
jsonhyperschema application/schema+json decoding
|
||||
json application/json data
|
||||
text text/* data
|
||||
|
||||
## Utilities
|
||||
|
||||
The command line client includes functionality for bookmarking API URLs
|
||||
under a memorable name. For example, you can add a bookmark for the
|
||||
existing API, like so...
|
||||
|
||||
$ coreapi bookmarks add accountmanagement
|
||||
|
||||
There is also functionality for navigating forward or backward through the
|
||||
history of which API URLs have been accessed.
|
||||
|
||||
$ coreapi history show
|
||||
$ coreapi history back
|
||||
|
||||
For more information and a listing of the available subcommands use
|
||||
`coreapi bookmarks --help` or `coreapi history --help`.
|
||||
|
||||
## Other commands
|
||||
|
||||
To display the current `Document`:
|
||||
|
||||
$ coreapi show
|
||||
|
||||
To reload the current `Document` from the network:
|
||||
|
||||
$ coreapi reload
|
||||
|
||||
To load a schema file from disk:
|
||||
|
||||
$ coreapi load my-api-schema.json --format corejson
|
||||
|
||||
To dump the current document to console in a given format:
|
||||
|
||||
$ coreapi dump --format openapi
|
||||
|
||||
To remove the current document, along with all currently saved history,
|
||||
credentials, headers and bookmarks:
|
||||
|
||||
$ coreapi clear
|
||||
|
||||
---
|
||||
|
||||
# Python client library
|
||||
|
||||
The `coreapi` Python package allows you to programmatically interact with any
|
||||
API that exposes a supported schema format.
|
||||
|
||||
## Getting started
|
||||
|
||||
You'll need to install the `coreapi` package using `pip` before you can get
|
||||
started.
|
||||
|
||||
$ pip install coreapi
|
||||
|
||||
In order to start working with an API, we first need a `Client` instance. The
|
||||
client holds any configuration around which codecs and transports are supported
|
||||
when interacting with an API, which allows you to provide for more advanced
|
||||
kinds of behaviour.
|
||||
|
||||
import coreapi
|
||||
client = coreapi.Client()
|
||||
|
||||
Once we have a `Client` instance, we can fetch an API schema from the network.
|
||||
|
||||
schema = client.get('https://api.example.org/')
|
||||
|
||||
The object returned from this call will be a `Document` instance, which is
|
||||
a representation of the API schema.
|
||||
|
||||
## Authentication
|
||||
|
||||
Typically you'll also want to provide some authentication credentials when
|
||||
instantiating the client.
|
||||
|
||||
#### Token authentication
|
||||
|
||||
The `TokenAuthentication` class can be used to support REST framework's built-in
|
||||
`TokenAuthentication`, as well as OAuth and JWT schemes.
|
||||
|
||||
auth = coreapi.auth.TokenAuthentication(
|
||||
scheme='JWT',
|
||||
token='<token>'
|
||||
)
|
||||
client = coreapi.Client(auth=auth)
|
||||
|
||||
When using TokenAuthentication you'll probably need to implement a login flow
|
||||
using the CoreAPI client.
|
||||
|
||||
A suggested pattern for this would be to initially make an unauthenticated client
|
||||
request to an "obtain token" endpoint
|
||||
|
||||
For example, using the "Django REST framework JWT" package
|
||||
|
||||
client = coreapi.Client()
|
||||
schema = client.get('https://api.example.org/')
|
||||
|
||||
action = ['api-token-auth', 'create']
|
||||
params = {"username": "example", "password": "secret"}
|
||||
result = client.action(schema, action, params)
|
||||
|
||||
auth = coreapi.auth.TokenAuthentication(
|
||||
scheme='JWT',
|
||||
token=result['token']
|
||||
)
|
||||
client = coreapi.Client(auth=auth)
|
||||
|
||||
#### Basic authentication
|
||||
|
||||
The `BasicAuthentication` class can be used to support HTTP Basic Authentication.
|
||||
|
||||
auth = coreapi.auth.BasicAuthentication(
|
||||
username='<username>',
|
||||
password='<password>'
|
||||
)
|
||||
client = coreapi.Client(auth=auth)
|
||||
|
||||
## Interacting with the API
|
||||
|
||||
Now that we have a client and have fetched our schema `Document`, we can now
|
||||
start to interact with the API:
|
||||
|
||||
users = client.action(schema, ['users', 'list'])
|
||||
|
||||
Some endpoints may include named parameters, which might be either optional or required:
|
||||
|
||||
new_user = client.action(schema, ['users', 'create'], params={"username": "max"})
|
||||
|
||||
## Codecs
|
||||
|
||||
Codecs are responsible for encoding or decoding Documents.
|
||||
|
||||
The decoding process is used by a client to take a bytestring of an API schema
|
||||
definition, and returning the Core API `Document` that represents that interface.
|
||||
|
||||
A codec should be associated with a particular media type, such as `'application/coreapi+json'`.
|
||||
|
||||
This media type is used by the server in the response `Content-Type` header,
|
||||
in order to indicate what kind of data is being returned in the response.
|
||||
|
||||
#### Configuring codecs
|
||||
|
||||
The codecs that are available can be configured when instantiating a client.
|
||||
The keyword argument used here is `decoders`, because in the context of a
|
||||
client the codecs are only for *decoding* responses.
|
||||
|
||||
In the following example we'll configure a client to only accept `Core JSON`
|
||||
and `JSON` responses. This will allow us to receive and decode a Core JSON schema,
|
||||
and subsequently to receive JSON responses made against the API.
|
||||
|
||||
from coreapi import codecs, Client
|
||||
|
||||
decoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()]
|
||||
client = Client(decoders=decoders)
|
||||
|
||||
#### Loading and saving schemas
|
||||
|
||||
You can use a codec directly, in order to load an existing schema definition,
|
||||
and return the resulting `Document`.
|
||||
|
||||
input_file = open('my-api-schema.json', 'rb')
|
||||
schema_definition = input_file.read()
|
||||
codec = codecs.CoreJSONCodec()
|
||||
schema = codec.load(schema_definition)
|
||||
|
||||
You can also use a codec directly to generate a schema definition given a `Document` instance:
|
||||
|
||||
schema_definition = codec.dump(schema)
|
||||
output_file = open('my-api-schema.json', 'rb')
|
||||
output_file.write(schema_definition)
|
||||
|
||||
## Transports
|
||||
|
||||
Transports are responsible for making network requests. The set of transports
|
||||
that a client has installed determines which network protocols it is able to
|
||||
support.
|
||||
|
||||
Currently the `coreapi` library only includes an HTTP/HTTPS transport, but
|
||||
other protocols can also be supported.
|
||||
|
||||
#### Configuring transports
|
||||
|
||||
The behavior of the network layer can be customized by configuring the
|
||||
transports that the client is instantiated with.
|
||||
|
||||
import requests
|
||||
from coreapi import transports, Client
|
||||
|
||||
credentials = {'api.example.org': 'Token 3bd44a009d16ff'}
|
||||
transports = transports.HTTPTransport(credentials=credentials)
|
||||
client = Client(transports=transports)
|
||||
|
||||
More complex customizations can also be achieved, for example modifying the
|
||||
underlying `requests.Session` instance to [attach transport adaptors][transport-adaptors]
|
||||
that modify the outgoing requests.
|
||||
|
||||
---
|
||||
|
||||
# JavaScript Client Library
|
||||
|
||||
The JavaScript client library allows you to interact with your API either from a browser, or using node.
|
||||
|
||||
## Installing the JavaScript client
|
||||
|
||||
There are two separate JavaScript resources that you need to include in your HTML pages in order to use the JavaScript client library. These are a static `coreapi.js` file, which contains the code for the dynamic client library, and a templated `schema.js` resource, which exposes your API schema.
|
||||
|
||||
First, install the API documentation views. These will include the schema resource that'll allow you to load the schema directly from an HTML page, without having to make an asynchronous AJAX call.
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
path('docs/', include_docs_urls(title='My API service'), name='api-docs'),
|
||||
]
|
||||
|
||||
Once the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed.
|
||||
|
||||
<!--
|
||||
Load the CoreAPI library and the API schema.
|
||||
|
||||
/static/rest_framework/js/coreapi-0.1.1.js
|
||||
/docs/schema.js
|
||||
-->
|
||||
{% load static %}
|
||||
<script src="{% static 'rest_framework/js/coreapi-0.1.1.js' %}"></script>
|
||||
<script src="{% url 'api-docs:schema-js' %}"></script>
|
||||
|
||||
The `coreapi` library, and the `schema` object will now both be available on the `window` instance.
|
||||
|
||||
const coreapi = window.coreapi;
|
||||
const schema = window.schema;
|
||||
|
||||
## Instantiating a client
|
||||
|
||||
In order to interact with the API you'll need a client instance.
|
||||
|
||||
var client = new coreapi.Client();
|
||||
|
||||
Typically you'll also want to provide some authentication credentials when
|
||||
instantiating the client.
|
||||
|
||||
#### Session authentication
|
||||
|
||||
The `SessionAuthentication` class allows session cookies to provide the user
|
||||
authentication. You'll want to provide a standard HTML login flow, to allow
|
||||
the user to login, and then instantiate a client using session authentication:
|
||||
|
||||
let auth = new coreapi.auth.SessionAuthentication({
|
||||
csrfCookieName: 'csrftoken',
|
||||
csrfHeaderName: 'X-CSRFToken',
|
||||
});
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
The authentication scheme will handle including a CSRF header in any outgoing
|
||||
requests for unsafe HTTP methods.
|
||||
|
||||
#### Token authentication
|
||||
|
||||
The `TokenAuthentication` class can be used to support REST framework's built-in
|
||||
`TokenAuthentication`, as well as OAuth and JWT schemes.
|
||||
|
||||
let auth = new coreapi.auth.TokenAuthentication({
|
||||
scheme: 'JWT',
|
||||
token: '<token>',
|
||||
});
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
When using TokenAuthentication you'll probably need to implement a login flow
|
||||
using the CoreAPI client.
|
||||
|
||||
A suggested pattern for this would be to initially make an unauthenticated client
|
||||
request to an "obtain token" endpoint
|
||||
|
||||
For example, using the "Django REST framework JWT" package
|
||||
|
||||
// Setup some globally accessible state
|
||||
window.client = new coreapi.Client();
|
||||
window.loggedIn = false;
|
||||
|
||||
function loginUser(username, password) {
|
||||
let action = ["api-token-auth", "obtain-token"];
|
||||
let params = {username: username, password: password};
|
||||
client.action(schema, action, params).then(function(result) {
|
||||
// On success, instantiate an authenticated client.
|
||||
let auth = window.coreapi.auth.TokenAuthentication({
|
||||
scheme: 'JWT',
|
||||
token: result['token'],
|
||||
})
|
||||
window.client = coreapi.Client({auth: auth});
|
||||
window.loggedIn = true;
|
||||
}).catch(function (error) {
|
||||
// Handle error case where eg. user provides incorrect credentials.
|
||||
})
|
||||
}
|
||||
|
||||
#### Basic authentication
|
||||
|
||||
The `BasicAuthentication` class can be used to support HTTP Basic Authentication.
|
||||
|
||||
let auth = new coreapi.auth.BasicAuthentication({
|
||||
username: '<username>',
|
||||
password: '<password>',
|
||||
})
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
## Using the client
|
||||
|
||||
Making requests:
|
||||
|
||||
let action = ["users", "list"];
|
||||
client.action(schema, action).then(function(result) {
|
||||
// Return value is in 'result'
|
||||
})
|
||||
|
||||
Including parameters:
|
||||
|
||||
let action = ["users", "create"];
|
||||
let params = {username: "example", email: "example@example.com"};
|
||||
client.action(schema, action, params).then(function(result) {
|
||||
// Return value is in 'result'
|
||||
})
|
||||
|
||||
Handling errors:
|
||||
|
||||
client.action(schema, action, params).then(function(result) {
|
||||
// Return value is in 'result'
|
||||
}).catch(function (error) {
|
||||
// Error value is in 'error'
|
||||
})
|
||||
|
||||
## Installation with node
|
||||
|
||||
The coreapi package is available on NPM.
|
||||
|
||||
$ npm install coreapi
|
||||
$ node
|
||||
const coreapi = require('coreapi')
|
||||
|
||||
You'll either want to include the API schema in your codebase directly, by copying it from the `schema.js` resource, or else load the schema asynchronously. For example:
|
||||
|
||||
let client = new coreapi.Client();
|
||||
let schema = null;
|
||||
client.get("https://api.example.org/").then(function(data) {
|
||||
// Load a CoreJSON API schema.
|
||||
schema = data;
|
||||
console.log('schema loaded');
|
||||
})
|
||||
|
||||
[heroku-api]: https://devcenter.heroku.com/categories/platform-api
|
||||
[heroku-example]: https://www.coreapi.org/tools-and-resources/example-services/#heroku-json-hyper-schema
|
||||
[core-api]: https://www.coreapi.org/
|
||||
[schema-generation]: ../api-guide/schemas.md
|
||||
[transport-adaptors]: http://docs.python-requests.org/en/master/user/advanced/#transport-adapters
|
|
@ -15,9 +15,23 @@ If you include fully-qualified URLs in your resource output, they will be 'urliz
|
|||
|
||||
By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview].
|
||||
|
||||
## Authentication
|
||||
|
||||
To quickly add authentication to the browesable api, add a routes named `"login"` and `"logout"` under the namespace `"rest_framework"`. DRF provides default routes for this which you can add to your urlconf:
|
||||
|
||||
```python
|
||||
from django.urls import include, path
|
||||
|
||||
urlpatterns = [
|
||||
# ...
|
||||
path("api-auth/", include("rest_framework.urls", namespace="rest_framework"))
|
||||
]
|
||||
```
|
||||
|
||||
|
||||
## Customizing
|
||||
|
||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), making it easy to customize the look-and-feel.
|
||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.4.1), making it easy to customize the look-and-feel.
|
||||
|
||||
To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example:
|
||||
|
||||
|
@ -35,7 +49,7 @@ To replace the default theme, add a `bootstrap_theme` block to your `api.html` a
|
|||
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
|
||||
Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. Make sure that the Bootstrap version of the new theme matches that of the default theme.
|
||||
|
||||
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
|
||||
|
||||
|
@ -44,7 +58,7 @@ Full example:
|
|||
{% extends "rest_framework/base.html" %}
|
||||
|
||||
{% block bootstrap_theme %}
|
||||
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@3.4.1/flatly/bootstrap.min.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
{% block bootstrap_navbar_variant %}{% endblock %}
|
||||
|
@ -65,6 +79,48 @@ For more specific CSS tweaks than simply overriding the default bootstrap theme
|
|||
|
||||
---
|
||||
|
||||
### Third party packages for customization
|
||||
|
||||
You can use a third party package for customization, rather than doing it by yourself. Here is 3 packages for customizing the API:
|
||||
|
||||
* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort.
|
||||
* [drf-redesign][drf-redesign] - A package for customizing the API using Bootstrap 5. Modern and sleek design, it comes with the support for dark mode.
|
||||
* [drf-material][drf-material] - Material design for Django REST Framework.
|
||||
|
||||
---
|
||||
|
||||
![API Root][drf-rw-api-root]
|
||||
|
||||
![List View][drf-rw-list-view]
|
||||
|
||||
![Detail View][drf-rw-detail-view]
|
||||
|
||||
*Screenshots of the drf-restwind*
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
![API Root][drf-r-api-root]
|
||||
|
||||
![List View][drf-r-list-view]
|
||||
|
||||
![Detail View][drf-r-detail-view]
|
||||
|
||||
*Screenshot of the drf-redesign*
|
||||
|
||||
---
|
||||
|
||||
![API Root][drf-m-api-root]
|
||||
|
||||
![List View][drf-m-api-root]
|
||||
|
||||
![Detail View][drf-m-api-root]
|
||||
|
||||
*Screenshot of the drf-material*
|
||||
|
||||
---
|
||||
|
||||
### Blocks
|
||||
|
||||
All of the blocks available in the browsable API base template that can be used in your `api.html`.
|
||||
|
@ -162,3 +218,15 @@ There are [a variety of packages for autocomplete widgets][autocomplete-packages
|
|||
[bcomponentsnav]: https://getbootstrap.com/2.3.2/components.html#navbar
|
||||
[autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/
|
||||
[django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light
|
||||
[drf-restwind]: https://github.com/youzarsiph/drf-restwind
|
||||
[drf-rw-api-root]: ../img/drf-rw-api-root.png
|
||||
[drf-rw-list-view]: ../img/drf-rw-list-view.png
|
||||
[drf-rw-detail-view]: ../img/drf-rw-detail-view.png
|
||||
[drf-redesign]: https://github.com/youzarsiph/drf-redesign
|
||||
[drf-r-api-root]: ../img/drf-r-api-root.png
|
||||
[drf-r-list-view]: ../img/drf-r-list-view.png
|
||||
[drf-r-detail-view]: ../img/drf-r-detail-view.png
|
||||
[drf-material]: https://github.com/youzarsiph/drf-material
|
||||
[drf-m-api-root]: ../img/drf-m-api-root.png
|
||||
[drf-m-list-view]: ../img/drf-m-list-view.png
|
||||
[drf-m-detail-view]: ../img/drf-m-detail-view.png
|
||||
|
|
|
@ -4,12 +4,42 @@
|
|||
>
|
||||
> — Roy Fielding, [REST APIs must be hypertext driven][cite]
|
||||
|
||||
REST framework provides built-in support for generating OpenAPI schemas, which
|
||||
can be used with tools that allow you to build API documentation.
|
||||
REST framework provides a range of different choices for documenting your API. The following
|
||||
is a non-exhaustive list of the most popular ones.
|
||||
|
||||
There are also a number of great third-party documentation packages available.
|
||||
## Third party packages for OpenAPI support
|
||||
|
||||
## Generating documentation from OpenAPI schemas
|
||||
### drf-spectacular
|
||||
|
||||
[drf-spectacular][drf-spectacular] is an [OpenAPI 3][open-api] schema generation library with explicit
|
||||
focus on extensibility, customizability and client generation. It is the recommended way for
|
||||
generating and presenting OpenAPI schemas.
|
||||
|
||||
The library aims to extract as much schema information as possible, while providing decorators and extensions for easy
|
||||
customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
|
||||
i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
|
||||
documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
|
||||
|
||||
### drf-yasg
|
||||
|
||||
[drf-yasg][drf-yasg] is a [Swagger / OpenAPI 2][swagger] generation tool implemented without using the schema generation provided
|
||||
by Django Rest Framework.
|
||||
|
||||
It aims to implement as much of the [OpenAPI 2][open-api] specification as possible - nested schemas, named models,
|
||||
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
|
||||
generation tools like `swagger-codegen`.
|
||||
|
||||
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
|
||||
|
||||
![Screenshot - drf-yasg][image-drf-yasg]
|
||||
|
||||
---
|
||||
|
||||
## Built-in OpenAPI schema generation (deprecated)
|
||||
|
||||
**Deprecation notice: REST framework's built-in support for generating OpenAPI schemas is
|
||||
deprecated in favor of 3rd party packages that can provide this functionality instead.
|
||||
As replacement, we recommend using the [drf-spectacular](#drf-spectacular) package.**
|
||||
|
||||
There are a number of packages available that allow you to generate HTML
|
||||
documentation pages from OpenAPI schemas.
|
||||
|
@ -66,10 +96,14 @@ urlpatterns = [
|
|||
# ...
|
||||
# Route TemplateView to serve Swagger UI template.
|
||||
# * Provide `extra_context` with view name of `SchemaView`.
|
||||
path('swagger-ui/', TemplateView.as_view(
|
||||
template_name='swagger-ui.html',
|
||||
extra_context={'schema_url':'openapi-schema'}
|
||||
), name='swagger-ui'),
|
||||
path(
|
||||
"swagger-ui/",
|
||||
TemplateView.as_view(
|
||||
template_name="swagger-ui.html",
|
||||
extra_context={"schema_url": "openapi-schema"},
|
||||
),
|
||||
name="swagger-ui",
|
||||
),
|
||||
]
|
||||
```
|
||||
|
||||
|
@ -115,44 +149,18 @@ urlpatterns = [
|
|||
# ...
|
||||
# Route TemplateView to serve the ReDoc template.
|
||||
# * Provide `extra_context` with view name of `SchemaView`.
|
||||
path('redoc/', TemplateView.as_view(
|
||||
template_name='redoc.html',
|
||||
extra_context={'schema_url':'openapi-schema'}
|
||||
), name='redoc'),
|
||||
path(
|
||||
"redoc/",
|
||||
TemplateView.as_view(
|
||||
template_name="redoc.html", extra_context={"schema_url": "openapi-schema"}
|
||||
),
|
||||
name="redoc",
|
||||
),
|
||||
]
|
||||
```
|
||||
|
||||
See the [ReDoc documentation][redoc] for advanced usage.
|
||||
|
||||
## Third party packages
|
||||
|
||||
There are a number of mature third-party packages for providing API documentation.
|
||||
|
||||
#### drf-yasg - Yet Another Swagger Generator
|
||||
|
||||
[drf-yasg][drf-yasg] is a [Swagger][swagger] generation tool implemented without using the schema generation provided
|
||||
by Django Rest Framework.
|
||||
|
||||
It aims to implement as much of the [OpenAPI][open-api] specification as possible - nested schemas, named models,
|
||||
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
|
||||
generation tools like `swagger-codegen`.
|
||||
|
||||
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
|
||||
|
||||
|
||||
![Screenshot - drf-yasg][image-drf-yasg]
|
||||
|
||||
#### drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework
|
||||
|
||||
[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility,
|
||||
customizability and client generation. Usage patterns are very similar to [drf-yasg][drf-yasg].
|
||||
|
||||
It aims to extract as much schema information as possible, while providing decorators and extensions for easy
|
||||
customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
|
||||
i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
|
||||
documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
|
||||
|
||||
---
|
||||
|
||||
## Self describing APIs
|
||||
|
||||
|
|
|
@ -1,220 +1,220 @@
|
|||
# HTML & Forms
|
||||
|
||||
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.
|
||||
|
||||
## Rendering HTML
|
||||
|
||||
In order to return HTML responses you'll need to use either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
|
||||
|
||||
The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
|
||||
|
||||
The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content.
|
||||
|
||||
Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
|
||||
|
||||
Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template:
|
||||
|
||||
**views.py**:
|
||||
|
||||
from my_project.example.models import Profile
|
||||
from rest_framework.renderers import TemplateHTMLRenderer
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
||||
class ProfileList(APIView):
|
||||
renderer_classes = [TemplateHTMLRenderer]
|
||||
template_name = 'profile_list.html'
|
||||
|
||||
def get(self, request):
|
||||
queryset = Profile.objects.all()
|
||||
return Response({'profiles': queryset})
|
||||
|
||||
**profile_list.html**:
|
||||
|
||||
<html><body>
|
||||
<h1>Profiles</h1>
|
||||
<ul>
|
||||
{% for profile in profiles %}
|
||||
<li>{{ profile.name }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</body></html>
|
||||
|
||||
## Rendering Forms
|
||||
|
||||
Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template.
|
||||
|
||||
The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
|
||||
|
||||
**views.py**:
|
||||
|
||||
from django.shortcuts import get_object_or_404
|
||||
from my_project.example.models import Profile
|
||||
from rest_framework.renderers import TemplateHTMLRenderer
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
||||
class ProfileDetail(APIView):
|
||||
renderer_classes = [TemplateHTMLRenderer]
|
||||
template_name = 'profile_detail.html'
|
||||
|
||||
def get(self, request, pk):
|
||||
profile = get_object_or_404(Profile, pk=pk)
|
||||
serializer = ProfileSerializer(profile)
|
||||
return Response({'serializer': serializer, 'profile': profile})
|
||||
|
||||
def post(self, request, pk):
|
||||
profile = get_object_or_404(Profile, pk=pk)
|
||||
serializer = ProfileSerializer(profile, data=request.data)
|
||||
if not serializer.is_valid():
|
||||
return Response({'serializer': serializer, 'profile': profile})
|
||||
serializer.save()
|
||||
return redirect('profile-list')
|
||||
|
||||
**profile_detail.html**:
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
<html><body>
|
||||
|
||||
<h1>Profile - {{ profile.name }}</h1>
|
||||
|
||||
<form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
|
||||
{% csrf_token %}
|
||||
{% render_form serializer %}
|
||||
<input type="submit" value="Save">
|
||||
</form>
|
||||
|
||||
</body></html>
|
||||
|
||||
### Using template packs
|
||||
|
||||
The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields.
|
||||
|
||||
REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
|
||||
|
||||
The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
|
||||
|
||||
<head>
|
||||
…
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
|
||||
</head>
|
||||
|
||||
Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
|
||||
|
||||
Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form.
|
||||
|
||||
class LoginSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField(
|
||||
max_length=100,
|
||||
style={'placeholder': 'Email', 'autofocus': True}
|
||||
)
|
||||
password = serializers.CharField(
|
||||
max_length=100,
|
||||
style={'input_type': 'password', 'placeholder': 'Password'}
|
||||
)
|
||||
remember_me = serializers.BooleanField()
|
||||
|
||||
---
|
||||
|
||||
#### `rest_framework/vertical`
|
||||
|
||||
Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
|
||||
|
||||
*This is the default template pack.*
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
...
|
||||
|
||||
<form action="{% url 'login' %}" method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% render_form serializer template_pack='rest_framework/vertical' %}
|
||||
<button type="submit" class="btn btn-default">Sign in</button>
|
||||
</form>
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
#### `rest_framework/horizontal`
|
||||
|
||||
Presents labels and controls alongside each other, using a 2/10 column split.
|
||||
|
||||
*This is the form style used in the browsable API and admin renderers.*
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
...
|
||||
|
||||
<form class="form-horizontal" action="{% url 'login' %}" method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% render_form serializer %}
|
||||
<div class="form-group">
|
||||
<div class="col-sm-offset-2 col-sm-10">
|
||||
<button type="submit" class="btn btn-default">Sign in</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
#### `rest_framework/inline`
|
||||
|
||||
A compact form style that presents all the controls inline.
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
...
|
||||
|
||||
<form class="form-inline" action="{% url 'login' %}" method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% render_form serializer template_pack='rest_framework/inline' %}
|
||||
<button type="submit" class="btn btn-default">Sign in</button>
|
||||
</form>
|
||||
|
||||

|
||||
|
||||
## Field styles
|
||||
|
||||
Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used.
|
||||
|
||||
The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use.
|
||||
|
||||
For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this:
|
||||
|
||||
details = serializers.CharField(
|
||||
max_length=1000,
|
||||
style={'base_template': 'textarea.html'}
|
||||
)
|
||||
|
||||
If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name:
|
||||
|
||||
details = serializers.CharField(
|
||||
max_length=1000,
|
||||
style={'template': 'my-field-templates/custom-input.html'}
|
||||
)
|
||||
|
||||
Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control.
|
||||
|
||||
details = serializers.CharField(
|
||||
max_length=1000,
|
||||
style={'base_template': 'textarea.html', 'rows': 10}
|
||||
)
|
||||
|
||||
The complete list of `base_template` options and their associated style options is listed below.
|
||||
|
||||
base_template | Valid field types | Additional style options
|
||||
----|----|----
|
||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||
select.html | `ChoiceField` or relational field types | hide_label
|
||||
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
||||
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
||||
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
|
||||
checkbox.html | `BooleanField` | hide_label
|
||||
fieldset.html | Nested serializer | hide_label
|
||||
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
||||
# HTML & Forms
|
||||
|
||||
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates.
|
||||
|
||||
## Rendering HTML
|
||||
|
||||
In order to return HTML responses you'll need to use either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
|
||||
|
||||
The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
|
||||
|
||||
The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content.
|
||||
|
||||
Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
|
||||
|
||||
Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template:
|
||||
|
||||
**views.py**:
|
||||
|
||||
from my_project.example.models import Profile
|
||||
from rest_framework.renderers import TemplateHTMLRenderer
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
||||
class ProfileList(APIView):
|
||||
renderer_classes = [TemplateHTMLRenderer]
|
||||
template_name = 'profile_list.html'
|
||||
|
||||
def get(self, request):
|
||||
queryset = Profile.objects.all()
|
||||
return Response({'profiles': queryset})
|
||||
|
||||
**profile_list.html**:
|
||||
|
||||
<html><body>
|
||||
<h1>Profiles</h1>
|
||||
<ul>
|
||||
{% for profile in profiles %}
|
||||
<li>{{ profile.name }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</body></html>
|
||||
|
||||
## Rendering Forms
|
||||
|
||||
Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template.
|
||||
|
||||
The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
|
||||
|
||||
**views.py**:
|
||||
|
||||
from django.shortcuts import get_object_or_404
|
||||
from my_project.example.models import Profile
|
||||
from rest_framework.renderers import TemplateHTMLRenderer
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
||||
class ProfileDetail(APIView):
|
||||
renderer_classes = [TemplateHTMLRenderer]
|
||||
template_name = 'profile_detail.html'
|
||||
|
||||
def get(self, request, pk):
|
||||
profile = get_object_or_404(Profile, pk=pk)
|
||||
serializer = ProfileSerializer(profile)
|
||||
return Response({'serializer': serializer, 'profile': profile})
|
||||
|
||||
def post(self, request, pk):
|
||||
profile = get_object_or_404(Profile, pk=pk)
|
||||
serializer = ProfileSerializer(profile, data=request.data)
|
||||
if not serializer.is_valid():
|
||||
return Response({'serializer': serializer, 'profile': profile})
|
||||
serializer.save()
|
||||
return redirect('profile-list')
|
||||
|
||||
**profile_detail.html**:
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
<html><body>
|
||||
|
||||
<h1>Profile - {{ profile.name }}</h1>
|
||||
|
||||
<form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
|
||||
{% csrf_token %}
|
||||
{% render_form serializer %}
|
||||
<input type="submit" value="Save">
|
||||
</form>
|
||||
|
||||
</body></html>
|
||||
|
||||
### Using template packs
|
||||
|
||||
The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields.
|
||||
|
||||
REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
|
||||
|
||||
The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
|
||||
|
||||
<head>
|
||||
…
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
|
||||
</head>
|
||||
|
||||
Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
|
||||
|
||||
Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form.
|
||||
|
||||
class LoginSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField(
|
||||
max_length=100,
|
||||
style={'placeholder': 'Email', 'autofocus': True}
|
||||
)
|
||||
password = serializers.CharField(
|
||||
max_length=100,
|
||||
style={'input_type': 'password', 'placeholder': 'Password'}
|
||||
)
|
||||
remember_me = serializers.BooleanField()
|
||||
|
||||
---
|
||||
|
||||
#### `rest_framework/vertical`
|
||||
|
||||
Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
|
||||
|
||||
*This is the default template pack.*
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
...
|
||||
|
||||
<form action="{% url 'login' %}" method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% render_form serializer template_pack='rest_framework/vertical' %}
|
||||
<button type="submit" class="btn btn-default">Sign in</button>
|
||||
</form>
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
#### `rest_framework/horizontal`
|
||||
|
||||
Presents labels and controls alongside each other, using a 2/10 column split.
|
||||
|
||||
*This is the form style used in the browsable API and admin renderers.*
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
...
|
||||
|
||||
<form class="form-horizontal" action="{% url 'login' %}" method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% render_form serializer %}
|
||||
<div class="form-group">
|
||||
<div class="col-sm-offset-2 col-sm-10">
|
||||
<button type="submit" class="btn btn-default">Sign in</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
#### `rest_framework/inline`
|
||||
|
||||
A compact form style that presents all the controls inline.
|
||||
|
||||
{% load rest_framework %}
|
||||
|
||||
...
|
||||
|
||||
<form class="form-inline" action="{% url 'login' %}" method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% render_form serializer template_pack='rest_framework/inline' %}
|
||||
<button type="submit" class="btn btn-default">Sign in</button>
|
||||
</form>
|
||||
|
||||

|
||||
|
||||
## Field styles
|
||||
|
||||
Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used.
|
||||
|
||||
The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use.
|
||||
|
||||
For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this:
|
||||
|
||||
details = serializers.CharField(
|
||||
max_length=1000,
|
||||
style={'base_template': 'textarea.html'}
|
||||
)
|
||||
|
||||
If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name:
|
||||
|
||||
details = serializers.CharField(
|
||||
max_length=1000,
|
||||
style={'template': 'my-field-templates/custom-input.html'}
|
||||
)
|
||||
|
||||
Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control.
|
||||
|
||||
details = serializers.CharField(
|
||||
max_length=1000,
|
||||
style={'base_template': 'textarea.html', 'rows': 10}
|
||||
)
|
||||
|
||||
The complete list of `base_template` options and their associated style options is listed below.
|
||||
|
||||
base_template | Valid field types | Additional style options
|
||||
-----------------------|-------------------------------------------------------------|-----------------------------------------------
|
||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||
select.html | `ChoiceField` or relational field types | hide_label
|
||||
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
||||
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
||||
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
|
||||
checkbox.html | `BooleanField` | hide_label
|
||||
fieldset.html | Nested serializer | hide_label
|
||||
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
||||
|
|
|
@ -17,9 +17,9 @@ You can change the default language by using the standard Django `LANGUAGE_CODE`
|
|||
|
||||
LANGUAGE_CODE = "es-es"
|
||||
|
||||
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting:
|
||||
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE` setting:
|
||||
|
||||
MIDDLEWARE_CLASSES = [
|
||||
MIDDLEWARE = [
|
||||
...
|
||||
'django.middleware.locale.LocaleMiddleware'
|
||||
]
|
||||
|
@ -90,7 +90,7 @@ If you're only translating custom error messages that exist inside your project
|
|||
|
||||
## How the language is determined
|
||||
|
||||
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES` setting.
|
||||
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE` setting.
|
||||
|
||||
You can find more information on how the language preference is determined in the [Django documentation][django-language-preference]. For reference, the method is:
|
||||
|
||||
|
@ -105,7 +105,7 @@ For API clients the most appropriate of these will typically be to use the `Acce
|
|||
[cite]: https://youtu.be/Wa0VfS2q94Y
|
||||
[django-translation]: https://docs.djangoproject.com/en/stable/topics/i18n/translation
|
||||
[custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling
|
||||
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
|
||||
[transifex-project]: https://explore.transifex.com/django-rest-framework-1/django-rest-framework/
|
||||
[django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po
|
||||
[django-language-preference]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#how-django-discovers-language-preference
|
||||
[django-locale-paths]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-LOCALE_PATHS
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
>
|
||||
> — Mike Amundsen, [REST fest 2012 keynote][cite].
|
||||
|
||||
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
|
||||
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to ensure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
|
||||
|
||||
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o
|
|||
|
||||
---
|
||||
|
||||
**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
|
||||
**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. Feel free to clone the repository and see the code in action.
|
||||
|
||||
---
|
||||
|
||||
|
@ -45,7 +45,7 @@ We'll need to add our new `snippets` app and the `rest_framework` app to `INSTAL
|
|||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
'snippets.apps.SnippetsConfig',
|
||||
'snippets',
|
||||
]
|
||||
|
||||
Okay, we're ready to roll.
|
||||
|
@ -77,7 +77,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
|
|||
We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
|
||||
|
||||
python manage.py makemigrations snippets
|
||||
python manage.py migrate
|
||||
python manage.py migrate snippets
|
||||
|
||||
## Creating a Serializer class
|
||||
|
||||
|
@ -150,7 +150,7 @@ At this point we've translated the model instance into Python native datatypes.
|
|||
|
||||
content = JSONRenderer().render(serializer.data)
|
||||
content
|
||||
# b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}'
|
||||
# b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}'
|
||||
|
||||
Deserialization is similar. First we parse a stream into Python native datatypes...
|
||||
|
||||
|
@ -165,7 +165,7 @@ Deserialization is similar. First we parse a stream into Python native datatype
|
|||
serializer.is_valid()
|
||||
# True
|
||||
serializer.validated_data
|
||||
# OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
|
||||
# {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}
|
||||
serializer.save()
|
||||
# <Snippet: Snippet object>
|
||||
|
||||
|
@ -175,11 +175,11 @@ We can also serialize querysets instead of model instances. To do so we simply
|
|||
|
||||
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
|
||||
serializer.data
|
||||
# [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('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': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}]
|
||||
|
||||
## Using ModelSerializers
|
||||
|
||||
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
|
||||
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
|
||||
|
||||
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
|
||||
|
||||
|
@ -307,8 +307,8 @@ Quit out of the shell...
|
|||
Validating models...
|
||||
|
||||
0 errors found
|
||||
Django version 1.11, using settings 'tutorial.settings'
|
||||
Development server is running at http://127.0.0.1:8000/
|
||||
Django version 5.0, using settings 'tutorial.settings'
|
||||
Starting Development server at http://127.0.0.1:8000/
|
||||
Quit the server with CONTROL-C.
|
||||
|
||||
In another terminal window, we can test the server.
|
||||
|
@ -321,42 +321,50 @@ You can install httpie using pip:
|
|||
|
||||
Finally, we can get a list of all of the snippets:
|
||||
|
||||
http http://127.0.0.1:8000/snippets/
|
||||
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": 3,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
]
|
||||
|
||||
Or we can get a particular snippet by referencing its id:
|
||||
|
||||
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"
|
||||
}
|
||||
]
|
||||
|
||||
Or we can get a particular snippet by referencing its id:
|
||||
|
||||
http http://127.0.0.1:8000/snippets/2/
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
...
|
||||
{
|
||||
"id": 2,
|
||||
"title": "",
|
||||
"code": "print(\"hello, world\")\n",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
|
||||
Similarly, you can have the same json displayed by visiting these URLs in a web browser.
|
||||
|
@ -371,8 +379,7 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
|
|||
|
||||
[quickstart]: quickstart.md
|
||||
[repo]: https://github.com/encode/rest-framework-tutorial
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[venv]: https://docs.python.org/3/library/venv.html
|
||||
[tut-2]: 2-requests-and-responses.md
|
||||
[httpie]: https://github.com/jakubroztocil/httpie#installation
|
||||
[httpie]: https://github.com/httpie/httpie#installation
|
||||
[curl]: https://curl.haxx.se/
|
||||
|
|
|
@ -29,7 +29,7 @@ REST framework provides two wrappers you can use to write API views.
|
|||
|
||||
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
|
||||
|
||||
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
||||
The wrappers also provide behavior such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
||||
|
||||
## Pulling it all together
|
||||
|
||||
|
@ -112,7 +112,7 @@ Now update the `snippets/urls.py` file slightly, to append a set of `format_suff
|
|||
|
||||
urlpatterns = [
|
||||
path('snippets/', views.snippet_list),
|
||||
path('snippets/<int:pk>', views.snippet_detail),
|
||||
path('snippets/<int:pk>/', views.snippet_detail),
|
||||
]
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||
|
|
|
@ -79,9 +79,9 @@ Okay, we're done. If you run the development server everything should be workin
|
|||
|
||||
## Using mixins
|
||||
|
||||
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.
|
||||
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
|
||||
|
||||
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 behaviour are implemented in REST framework's mixin classes.
|
||||
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.
|
||||
|
||||
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
|
||||
|
||||
|
|
|
@ -38,7 +38,7 @@ And now we can add a `.save()` method to our model class:
|
|||
formatter = HtmlFormatter(style=self.style, linenos=linenos,
|
||||
full=True, **options)
|
||||
self.highlighted = highlight(self.code, lexer, formatter)
|
||||
super(Snippet, self).save(*args, **kwargs)
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
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.
|
||||
|
|