An API (Application Programming Interface) is a standardized interface that let two machines talk to each other. In this tutorial, we’ll be covering how to build an API with Masonite.

Prerequisites

To understand this tutorial, you have to :

  • Understand Python basics;
  • Understand basics Masonite

For this tutorial, I’ll use the previous project from the article Database Seeding with Masonite. You can clone it here (Be sure to choose the database-seeding branch) and follow the installation process in README.md file.

What is Masonite API?

Masonite API is package created to make it very very simple to create externally API. Install it via pip

pip install masonite-api

Masonite is service provider. To use it, we have to regsiter it in the provider list.

#config/providers.py
...
from masonite.api.providers import ApiProvider

PROVIDERS = [
  #..

  # Third Party Providers
  ApiProvider,
]

Adding the Guard

The next step is to configure the guard of Masonite API guard. It’s useful when you want to authenticate users and requests using an API token in the header (bearer) or query parameter.

#config/auth.py
...
from app.Post import Post
...
    'guards': {
        'web': {
            # ..
            # Normal config here
            # ..
        },
        'api': {
            'driver': 'jwt',
            'model': User,
        },
    }

Creating Resources

A resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it. In Masonite, resources are linked to models (orator models). Let’s create a directory in app like app/resources

from masonite.api.resources import Resource
from app.Post import Post

class PostResource(Resource):
    model = Post

For an working and effective API, serializers are very important. Here we’ll use the JsonResponseMiddleWare to return a dictionary. The dictionary is just the serialized data of the model (Orator models).

Specifying the routes

The resource package comes with several built-in routes we can easily add to the web.py file.

...
from app.resources.PostResource import PostResource
ROUTES = [
  ...
  PostResource('/api/posts').routes(),
    ...
]

In the terminal, check the new routes :

craft show:routes

output :

==========  =============  =======  ========  ============
Method      Path           Name     Domain    Middleware
==========  =============  =======  ========  ============
['GET']     /              welcome
['GET']     /posts         posts
['POST']    api/posts
['GET']     api/posts
['GET']     api/posts/@id
['PUT']     api/posts/@id
['DELETE']  api/posts/@id
==========  =============  =======  ========  ============

As you can see, you have all the routes available. However, we don’t want to use them all. Let’s add the methods attribute.

class PostResource(Resource, JSONSerializer):
    model = Post
    methods = ['index','show']

Then, run again : craft show:routes. Conclusion This is the basics of how to use masonite-api package to easily create REST API. By using Postman or your navigator, you can get all the posts or each post.

The next step will be to configure methods to delete, create, or modify posts.

If you have any questions or recommendations, you are welcome in the comment section.