Skip to main content

REST API framework based on FastAPI

Project description

Freenit Backend

Initialize the Project

python -m venv ~/.virtualenvs/myproject
source ~/.virtualenvs/myproject/bin/activate
pip install freenit[dev]
freenit.sh myproject
cd myproject
bin/devel.sh

It will create initial DB migration, apply it and start local development server so you can check if everything is OK.

Model

Let's say you want to add the simplest model for blog post with only title and contents. In your project's models directory you need to create blog.py:

import ormar

from freenit.config import getConfig
from freenit.models.base import BaseModel
from freenit.models.metaclass import AllOptional

config = getConfig()


class Blog(BaseModel):
    class Meta(config.meta):
        pass

    id: int = ormar.Integer(primary_key=True)
    title: str = ormar.String(max_length=1024)
    content: str = ormar.Text()



class BlogOptional(Blog, metaclass=AllOptional):
    pass

Please note two things: BaseModel is Freenit class not Ormar and BlogOptional is for PATCH method so all it's fields are the same as Blog except they are optional. The reason for this is that Ormar models are not just for DB operations, but for validating JSON input and parsing objects into JSON.

Endpoint

In api directory of your project add blog.py with the following content:

from typing import List

import ormar
from fastapi import HTTPException
from freenit.router import route

from ..models.blog import Blog, BlogOptional


@route('/blogs', tags=['blog'])
class BlogListAPI():
    @staticmethod
    async def get() -> List[Blog]:
        return await Blog.objects.all()

    @staticmethod
    async def post(blog: Blog) -> Blog:
        await blog.save()
        return blog


@route('/blogs/{id}', tags=['blog'])
class BlogDetailAPI():
    @staticmethod
    async def get(id: int) -> Blog:
        try:
            blog = await Blog.objects.get(pk=id)
        except ormar.exceptions.NoMatch:
            raise HTTPException(status_code=404, detail="No such blog")
        return blog

    @staticmethod
    async def patch(id: int, blog_data: BlogOptional) -> Blog:
        try:
            blog = await Blog.objects.get(pk=id)
            await blog.patch(blog_data)
        except ormar.exceptions.NoMatch:
            raise HTTPException(status_code=404, detail="No such blog")
        return blog

    @staticmethod
    async def delete(id: str) -> Blog:
        try:
            blog = await Blog.objects.get(pk=id)
        except ormar.exceptions.NoMatch:
            raise HTTPException(status_code=404, detail="No such blog")
        await blog.delete()
        return blog

What you have now is basic CRUD operations on your blog. Note that @route is Freenit's decorator to make it easy to write class based endpoints. As FastAPI itself has great support for function based endpoints, the idea was to make it possible for developer to choose between functions and classes. With Freenit you can write any style you want. Also note that class methods are static (decorated with @staticmethod) because API classes will never create an object. Or in other words, methods are going to be called on class, not object. Also, return value type hinting is important. It will tell Freenit what object is returned from the method and how to convert it to JSON.

DB Migration

To connect it all, you need to add the following to api/__init__.py:

import myproject.api.blog

After that you need to create migration. To do that run the following command from myproject directory:

alembic revision --autogenerate -m blog

It will create new migration file in alembic/versions and format it with black. Next time you run bin/devel.sh that migration will be applied.

Now you should see Blog endpoint in Swagger

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

freenit-0.2.12.tar.gz (27.6 kB view details)

Uploaded Source

Built Distribution

freenit-0.2.12-py3-none-any.whl (23.0 kB view details)

Uploaded Python 3

File details

Details for the file freenit-0.2.12.tar.gz.

File metadata

  • Download URL: freenit-0.2.12.tar.gz
  • Upload date:
  • Size: 27.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.5.0 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.12

File hashes

Hashes for freenit-0.2.12.tar.gz
Algorithm Hash digest
SHA256 4d74f647f7c8bcd9429f1b4c343df6288b14be2dae372e2db3ae5322b5c9f376
MD5 22fb01dc4a40451a02881f3fa5fb0d01
BLAKE2b-256 e836e10ff8a238686a54269e51858dcf00b3219452e45e91b176cb6d7b8179da

See more details on using hashes here.

File details

Details for the file freenit-0.2.12-py3-none-any.whl.

File metadata

  • Download URL: freenit-0.2.12-py3-none-any.whl
  • Upload date:
  • Size: 23.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.5.0 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.12

File hashes

Hashes for freenit-0.2.12-py3-none-any.whl
Algorithm Hash digest
SHA256 12c53cc3c88c2e80793c6eb70e988fc0a1f988a71a2ae2d96ce5f785f023d28e
MD5 89338724fb6e4416f1e5f214d412251d
BLAKE2b-256 ddfd7015e8e40db5a03b810d7549e94851f6a0703bed60c7fa00b5419933352b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page