Fastapi: Class based views

Created on 8 Apr 2019  路  6Comments  路  Source: tiangolo/fastapi

How to create class based views? Like this

from pyramid.view import (
    view_config,
    view_defaults
    )

@view_defaults(renderer='home.pt')
class TutorialViews:
    def __init__(self, request):
        self.request = request

    @view_config(route_name='home')
    def home(self):
        return {'name': 'Home View'}

    @view_config(route_name='hello')
    def hello(self):
        return {'name': 'Hello View'}

More info:
https://docs.pylonsproject.org/projects/pyramid/en/latest/quick_tutorial/view_classes.html

question

Most helpful comment

Here鈥檚 an approach I use to organize endpoints into classes (mostly so I don鈥檛 have to repeat all the dependencies in each signature): https://gist.github.com/dmontagu/87e9d3d7795b14b63388d4b16054f0ff

All 6 comments

From what I see from the example, that view is designed to render a template that changes slightly depending on the specific method/route, right?

I think that might not fit very well in an API. You can still declare independent routes/path operations that render templates, using a template engine like Jinja2. And you can use Starlette's class-based Endpoints in FastAPI, but then you wouldn't get all the benefits of FastAPI, with automatic data validation, serialization, documentation, dependency injection, etc.

Ahh ok didn' t knew about HTTPEndpoint. I think my example was a bit misleading i was thinking about POST;GET;PUT functions in a class like this:

@view_defaults(route_name='user', renderer='json')
class UserViews(object):

    def __init__(self, ...):
        pass

    @view_config(request_method='GET')
    def get(self):
        pass

    @view_config(request_method='PUT')
    def put(self):
        pass

    @view_config(request_method='DELETE')
    def delete(self):
        pass

I guess in that case you could do something like this:

from fastapi import FastAPI

app = FastAPI()

@app.get("/user/")
def read_user():
    pass

@app.put("/user/")
def update_user():
    pass

@app.post("/user/")
def create_user():
    pass

That's the closest example, but you probably would also pass some kind of parameter to the GET and PUT operations and validate it, and for the PUT and POST you would pass a JSON body and validate it.

All the validation and docs would be done automatically by FastAPI using it like above.

I'll assume this answers the question, so I'll close this issue now. But feel free to add more comments or create new issues.

It can be nice to group resources (_user_) by class for readability.

Something like:
https://flask-restful.readthedocs.io/en/latest/quickstart.html#a-minimal-api

Here鈥檚 an approach I use to organize endpoints into classes (mostly so I don鈥檛 have to repeat all the dependencies in each signature): https://gist.github.com/dmontagu/87e9d3d7795b14b63388d4b16054f0ff

Was this page helpful?
0 / 5 - 0 ratings