Creating Resources

Last updated 6 months ago

Introduction

Resources are classes which are used to specify API endpoints. You can think of resources as "API Resources". Models are connected to resources which give access to all CRUD operations for that model.

Getting Started

We can easily create new resources using the command that this package added to your craft commands.

$ craft entry:resource UserResource

This will create a new resource in app/http/resources/UserResource.py that is just boiler plate that we can use to build our resource. This new file should look like:

from entry.api.Resource import Resource
from entry.api.JsonSerialize import JsonSerialize
class UserResource(Resource, JsonSerialize):
model = None

We now just have to add the model we want to use for this resource. For this example we will use the User model that comes standard with every Masonite installation.

from entry.api.Resource import Resource
from entry.api.JsonSerialize import JsonSerialize
from app.User import User
class UserResource(Resource, JsonSerialize):
model = User

That's it! We now have complete CRUD operations for our model.

Using The Resource

You'll need to add the resource to your RESOURCES list inside routes/api.py:

from app.http.resources.UserResource import UserResource
RESOURCES = [
UserResource(),
]

Run the server using craft serve, open up your browser and head to localhost:8000/api/users which will show you all of your users.

If you don't have any users then you will only see:

[]

Meaning you don't have any models. Read the next set of documentation to learn how to use resources.

Next Steps

Read the Building The API documentation to learn how to use resources.