Skip to main content

Pretty tornado wrapper for making lightweight REST API services

Project description

PyPi Version

CleanAPI

Pretty tornado wrapper for making lightweight REST API services


Installation:

pip install cleanapi

Example:

Project folders structure:

.
├── handlers
│   └── simple_handler.py
├── log
├── ssl
│   ├── ca.csr
│   └── ca.key
├── static_html
│   └── index.html
└── server_example.py

server_example.py

from cleanapi import server

if __name__ == '__main__':
    # uses http protocol
    server.start('http', 8080, '/', './handlers', './static_html')

    # # uses https protocol
    # server.start('https', 8443, '/', './handlers', './static_html',
    #              path_to_ssl='./ssl', ssl_certfile_name='ca.csr', ssl_keyfile_name='ca.key')

simple_handler.py

from cleanapi.server import BaseHandler

url_tail = '/example.json'


# noinspection PyAbstractClass
class Handler(BaseHandler):
    """
    Test API request handler
    """
    async def get(self):
        self.set_status(200)
        self.write({'status': 'working'})

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Cleanapy demo</title>
  <link rel="icon" href="/favicon.ico" type="image/x-icon" />
 </head>
<body>

<h1>Cleanapy demo page</h1>

<p>Everything OK</p>

</body>
</html>

You also may put 'favicon.ico' file to the 'static_html' folder, but it is not necessary.

Then you can test server responses on http://localhost:8080 and http://localhost:8080/example.json

See log/cleanapi.log for information about externel access to the server


Example with PydanticHandler:

pydantic_handler.py

from cleanapi.server import PydanticHandler
from pydantic import BaseModel, validator, NonNegativeInt
from typing import Optional, List


url_tail = '/pydantic.json'


class PydanticRequest(BaseModel):
    """
    Pydantic dataclass for request
    """
    foo: NonNegativeInt
    bar: NonNegativeInt

    @validator('foo', 'bar')
    def _validate_foo_bar(cls, val: str):
        if val == 666:
            raise ValueError(f'Values of foo and bar should not be equal to 666')
        return val


class PydanticResponse(BaseModel):
    """
    Pydantic dataclass for response
    """
    summ: Optional[NonNegativeInt]
    errors: Optional[List[dict]]


# noinspection PyAbstractClass
class Handler(PydanticHandler):
    """
    Example of using PydanticHandler
    """
    request_dataclass = PydanticRequest
    result_dataclass = PydanticResponse

    # noinspection PyUnusedLocal
    def process(self, request: request_dataclass) -> result_dataclass:
        """
        What the handler should do
        :param request: incoming request
        :type request: request_dataclass
        :return: processing result
        :type: result_data class
        """
        result = PydanticResponse(summ=request.foo + request.bar, errors=[])

        if result.summ > 1000:
            raise ValueError('The sum of foo and bar is more than 1000')

        return result

    def if_exception(self, errors: list) -> None:
        """
        What to do if an exception was thrown
        :param errors: list of errors
        :type errors: list
        """
        self.set_status(400)
        self.write({'errors': errors})
        return

You can not test it with a browser because of POST method using. You have to use a program like Postman or some custom util like my pynger.py

Project details


Download files

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

Source Distribution

cleanapi-0.1.6.tar.gz (20.2 kB view details)

Uploaded Source

Built Distribution

cleanapi-0.1.6-py3-none-any.whl (21.2 kB view details)

Uploaded Python 3

File details

Details for the file cleanapi-0.1.6.tar.gz.

File metadata

  • Download URL: cleanapi-0.1.6.tar.gz
  • Upload date:
  • Size: 20.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.6.4 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.6

File hashes

Hashes for cleanapi-0.1.6.tar.gz
Algorithm Hash digest
SHA256 d022bf548fd7593c364a9cf5b6e67efbca6ad24149869d1ea6fbfdae94272d1c
MD5 4c29aef96a9ff15b75140a6202c8a336
BLAKE2b-256 a8e53c5653104a752f3ef90437ec68b1b98827cd4ebf68104fca295e263d8c91

See more details on using hashes here.

File details

Details for the file cleanapi-0.1.6-py3-none-any.whl.

File metadata

  • Download URL: cleanapi-0.1.6-py3-none-any.whl
  • Upload date:
  • Size: 21.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.6.4 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.2 CPython/3.9.6

File hashes

Hashes for cleanapi-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 ea04ca92a4a58be561f731b7663b5a17d92c0e436d7e29e76dd8b6cf6dbef10b
MD5 2b8dfee6546ec290ff49610943cb4a70
BLAKE2b-256 cfa2cb0d88a0f33a3810174ba9ebb2317bed0b33ed031bac85c6308626893df7

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