Getting started¶
To install Podiant API, simply run:
pip install podiant-api
Then add the app to your settings:
INSTALLED_APPS = (
...
'api',
...
)
There are no models, and the package does not come with its own URLconf.
Quickstart¶
The quickest way to create an API endpoint for a model is to use the REST shortcut.
Let’s say our app’s models.py file looks like this:
from django.db import models
class List(models.Model):
name = models.CharField(max_length=255)
creator = models.ForeignKey(
'auth.User',
related_name='lists',
on_delete=models.CASCADE
)
class Task(models.Model):
list = models.ForeignKey(
List,
related_name='tasks',
on_delete=models.CASCADE
)
name = models.CharField(max_length=255)
completed = models.BooleanField(default=False)
We would add the following to our app’s urls.py file:
from api.urls import rest
from django.contrib.auth.models import User
from .models import List, Task
urlpatterns = rest(
List,
fields=('name',),
readonly_fields=('creator',),
prepopulated_fields={
'creator': lambda request: request.user
},
relations=(
'creator',
'tasks'
)
) + rest(
Task,
fields=(
'name',
'completed'
),
relations=(
'creator',
'list'
)
) + rest(
User,
exclude=(
'email',
'password',
'is_superuser',
'is_staff',
'groups',
'user_permissions'
),
readonly_fields=(
'date_joined',
'last_login'
),
order_by=('last_name', 'first_name'),
relations={
'lists',
}
)
app_name = 'todos'
We now include our app’s URLconf in our project, like so:
from django.conf.urls import url, include
from .todos import urls as todos_urls
urlpatterns = [
url(r'^api/', include(todos_urls, 'api'))
]
We make sure to include the namespace argument. It must be set to ‘api’, and in Django>=2.0, the app’s URLconf must contain an app_name attribute.
This should expose the following URLs:
/api/lists/
/api/lists/<list_id>/
/api/lists/<list_id>/tasks/
/api/lists/<list_id>/relationships/tasks/
/api/lists/<list_id>/creator/
/api/lists/<list_id>/relationships/creator/
/api/tasks/
/api/tasks/<task_id>/
/api/lists/<list_id>/lists/
/api/lists/<list_id>/relationships/lists/
/api/users/
/api/users/<username>/
/api/users/<username>/lists/
/api/users/<username>/relationships/lists/
The /api/users/<username>/
URLs are a special case, as it uses the
API_URL_OVERRIDES setting
setting so that the username is used to identify the user instead of the primary
key.
JSON API¶
Podiant API is built to allow the easy creation of JSON-API-compliant endpoints. For more information, see the JSON API documentation.