Django REST Framework ViewSets — ELI5

Imagine you run a library. People come in and do the same kinds of things every day: browse books, check one out, return one, add a new book to the collection, or remove an old one. These actions repeat for every type of item — books, DVDs, magazines.

You could write separate instructions for each action on each item type. Or you could write one template: “For any collection of items, here’s how browsing, checking out, returning, adding, and removing works.” Then just say “apply this template to books” and “apply this template to DVDs.”

That’s what a ViewSet does in Django REST Framework (DRF). When you’re building an API — the part of a website that lets other programs request data — you end up writing the same operations over and over: list all items, get one item, create a new item, update an item, delete an item.

A ViewSet bundles all of these operations into one class. Instead of writing five separate pieces of code, you write one ViewSet and tell it which database table to work with. DRF figures out the rest: which URL goes to which action, how to format the data, and how to handle errors.

The magic comes from routers — they automatically create all the URL patterns your API needs. Register a ViewSet with a router, and you instantly get endpoints for listing, creating, reading, updating, and deleting.

The tradeoff is flexibility. ViewSets make standard CRUD (create, read, update, delete) almost automatic, but if your API does something unusual, you might fight the conventions instead of benefiting from them.

The one thing to remember: ViewSets let you build a complete REST API for a data model by writing one class instead of five — convention and automation do the repetitive work for you.

pythondjangorest-apidrf

See Also