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.
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 Resourcefrom entry.api.JsonSerialize import JsonSerializeclass 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 Resourcefrom entry.api.JsonSerialize import JsonSerializefrom app.User import Userclass UserResource(Resource, JsonSerialize):model = User
That's it! We now have complete CRUD operations for our model.
You'll need to add the resource to your RESOURCES
list inside routes/api.py
:
from app.http.resources.UserResource import UserResourceRESOURCES = [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.
Read the Building The API documentation to learn how to use resources.