Ray: a new python web framework

TL;DR: check the project here

Ray is a new python web framework to help you develop REST APIs. Ray provides features that are common to almost every backend who serves REST APIs. Let's check them:

Endpoints
Adding the @endpoint decorator to your model, you’ll have all HTTP methods (POST, DELETE, GET, PUT) to interact with your model through the url “/api/user”. Also, endpoints supports query string to the GET method (e.g: /api/user?age=99)
How to do it:

@endpoint(‘/user’)
class User(PeeweeModel):
name = peewee.CharField()
bio = peewee.TextField()
age = peewee.IntegerField()

Hooks
Hooks are useful to add validations in different moments of your application. Hook is a class that connect with your model and will be executed before save the model, after the model be saved or before the model be deleted.

class AgeValidationHook(Hook):
def before_save(self, user):
if user.age < 18:
raise Exception(‘The user must have more than 18 years’)
return True
@endpoint(‘/user’)
class User(PeeweeModel):
hooks = [AgeValidationHook]

Actions
Actions provide a simple way to you add a custom endpoints in your API. After writing the code bellow, you can use the url /api/user/<user_id>/activate to invoke the activate_user method.


class ActionUser(ActionAPI):
__model__ = User
    @action('/activate')
def activate_user(self, model_id):
user = User.get(id=model_id)
user.activate = True
user.put()

Authentication
Ray has a built-in authentication module. To use it, you just need to inherit the Authentication class and implement the method authenticate. In this method, you’ll check the data in the database and then return if the user can login or not.

class MyAuth(Authentication):
@classmethod
def authenticate(cls, username, password):
user = User.query(User.username == username,
User.password == password).one()
return {'username': 'ray'} if user else None
# If you want protect all the operations in this endpoint, you can just add this:
@endpoint('/person', authentication=MyAuth)
class PersonModel(ModelInterface):

After protect your endpoint via an Authentication, you will need to be logged in to don’t get a 403 status code. To do this use the urls: /api/_login and /api/_logout.

Shields
Ray has an option to you protect just some HTTP methods of your endpoint: using Shields. How does it works? You inherit from the Shield class and implement just the http method that you want to protect. The shield bellow protects the GET method of /api/person.

class PersonShield(Shield):
__model__ = PersonModel
   def get(self, user_data):
return user_data['profile'] == 'admin'
   # def put(self, user_data): pass
   # def post(self, user_data): pass
   # def delete(self, user_data): pass

Do you want to see more details about Ray? Check the project repository here!

Show your support

Clapping shows how much you appreciated felipe volpone’s story.