๐ป Views and Serializers in DRF ๐ป
Posted on Sep 15th, 2022
๐๏ธ Todayโs Topics
- Views and viewsets
- Nesting and customizing serializers
- Permissions
๐ฏ Project
Keep on with your API building ๐ ๐ช! What do you need to know to get it working?
By now you should have a list of endpoints that your API offers, even if they are not all complete yet. A good place to document this list of endpoints would be in your README, formatted with Markdown. This list should show the URLs along with the HTTP methods/verbs, and ideally should include an example of the JSON that has to be included in the request body (for any requests that send data in the body) and an example of the JSON response that will be returned, for each endpoint. This list will be helpful for your own testing and it can serve as necessary documentation for your API.
Here is an example of what your documentation might look like for an endpoint to create a book:
Create a new book
request
Requires authentication.
title
and author
are required fields.
POST api/books
{
"title": "The Anatomy of Melancholy",
"author": "Robert Burton",
"publication_year": 1621
}
response
201 Created
{
"pk": 6,
"title": "The Anatomy of Melancholy",
"author": "Robert Burton",
"publication_year": 1621,
"featured": false,
"reviews": []
}
By today or tomorrow, your app should respond with JSON data to GET requests for all habits(or books), for a single habit(or book), and for one habitโs (or bookโs) associated objects (daily records for habits; reviews or trackers for books). By tomorrow you should also have at least some of your POSTs working, and can begin working on UPDATE and DELETE.
๐ Make sure you test your endpoints in Insomnia to confirm that they are returning what they should, and NOT returning what they shouldnโt. Use show_urls
from django-extensions to help you check what urls you have defined.
Is your app deployed to Heroku yet? ๐ ๐
๐ Resources
Serializers
- Using Different Read and Write Serializers in DRF
- How to Save Extra Data to a DRF Serializer - for example, when you need to associate a user with an object that you are creating.
- Effectively using DRF Serializers
Permissions
- DRF Permissions
- Built-in Permission Classes in DRF
- Custom Permissions in DRF
- Pro Tip about DRF Permissions This shows how to combine permissions with logical operators like
and
andor