Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 72 ยท REST APIs

Class-Based Views and MethodView

Organize Flask endpoints as classes. Learn View, dispatch_request, as_view, MethodView, decorators and a reusable pattern for REST API resources.

Function views are Flask's default and they are great for small things. But a REST resource such as /books/<id> usually needs several verbs on the same URL: GET to read, PUT to replace, PATCH to edit, DELETE to remove. With functions you either write one view full of if request.method == ... branches or you write four decorated functions that all repeat the same URL and the same lookup code.

Class-based views solve this. A class groups the methods of one resource, can share setup code between them, can be subclassed, and can be configured when you register it. In this lesson you will use flask.views.View for custom dispatch, MethodView for the HTTP-verb-per-method style that REST APIs love, and a small helper that registers a whole resource in one line.

How a class becomes a view

Flask routes to callables, so a class cannot be registered directly. Instead you call YourClass.as_view("endpoint_name"), which returns a view function. On every request that function creates a fresh instance of your class and calls its dispatch_request() method.

flowchart LR
    R["request"] --> F["view function<br/>from as_view('items')"]
    F --> N["new ItemView() instance"]
    N --> D["dispatch_request()"]
    D --> M["your code runs<br/>and returns a response"]

The instance lives for one request only, so storing per-request data on self is safe.

The first argument of as_view is the endpoint name, the name you pass to url_for. Any further arguments are handed to the class's __init__, which makes configuration easy.

Python A plain View with dispatch_request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

View is most useful for sharing logic: a base class can implement dispatch_request once (load data, render a template) and subclasses override small hooks. For HTTP APIs there is an even better fit.

MethodView: one method per HTTP verb

flask.views.MethodView is a View whose dispatch_request looks at the HTTP method and calls the class method with the same lowercase name: get, post, put, patch, delete. You do not set methods yourself; Flask collects them from the methods you defined. Anything you did not define gets a 405 Method Not Allowed for free, with a correct Allow header.

Python A resource with MethodView

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the last two lines. PUT is not defined on BookDetail, so the response is 405 and the Allow header lists the verbs that do exist (plus HEAD and OPTIONS, which Flask adds automatically). The class attribute methods was filled in automatically.

One URL, two classes

The list and the detail endpoints have different URLs (/books and /books/<id>), so REST APIs conventionally use two classes per resource: a collection view (GET list, POST create) and an item view (GET, PUT, PATCH, DELETE). Many Flask projects follow this pairing.

A helper that registers a whole resource

Registering the same two URLs for every resource gets repetitive. A small function removes the repetition. It uses defaults to give the collection URL a None id, so one class can serve both URLs if you prefer that style:

Python register_api: one line per resource

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two things to notice. First, the same Resource class is used for two different resources; the store argument passed to as_view reaches __init__. Second, init_every_request = False tells Flask to create the instance once at registration and reuse it, which is slightly faster but means you must not keep per-request state on self. With the default (True) a fresh instance is built for every request, which is the safe choice and what you usually want.

Decorators on class-based views

You could decorate each method (get, post, ...) separately, but you would repeat yourself and might forget one. Use the class attribute decorators, a list applied to the view function that as_view returns. This is how you protect a whole resource with one line, for example a login or API-key check (the pattern is developed in API Authentication with Tokens).

Python Protect a whole class with decorators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Decorators listed in decorators wrap the whole view, so they run before dispatch_request and see the request before the HTTP method has been chosen. If you only want to protect some verbs, check inside those methods or build a base class that does it.

Function views or class views?

Neither is better. Prefer plain functions for a handful of simple routes. Reach for classes when:

  • one URL serves several HTTP verbs that share setup code,
  • you build many near-identical endpoints (a generic CRUD resource),
  • you want to configure a view when registering it (as_view("name", arg)),
  • you want to apply the same decorators to a group of verbs.

Larger apps also combine classes with Blueprints: register the views on a blueprint with bp.add_url_rule(...) exactly as shown above.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does BookDetail.as_view("book") return?

    as_view returns a normal view function. The string is the endpoint name used by url_for. By default Flask creates a new instance of the class for each request.
  2. 2. A MethodView defines only get and post. What happens on a DELETE request to its URL?

    MethodView derives the allowed methods from the methods you define. Anything else is automatically rejected with 405.
  3. 3. How do extra arguments given to as_view("name", a, b) reach your class?

    as_view forwards its extra arguments to the constructor, which lets you configure the same class differently for several URLs.
  4. 4. Where do you attach a login check that should protect every method of a MethodView?

    The decorators list is applied to the view function returned by as_view, so every HTTP method of the class is covered.

Summary

  • View.as_view("endpoint", *args) turns a class into a view function; each request gets an instance and dispatch_request runs.
  • MethodView maps HTTP verbs to methods (get, post, put, patch, delete); undefined verbs give 405 with a correct Allow header.
  • URL variables are passed to the methods as arguments; extra as_view arguments go to __init__.
  • Use one class for the collection and one for the item, or one class with defaults={"id": None}, and wrap the registration in a helper such as register_api.
  • decorators = [...] wraps the whole view; init_every_request = False reuses one instance when it holds no per-request state.
  • Use plain functions for simple routes and classes when verbs share code.

Next, make the data going in and out of these views reliable with Validation and Serialization.