Async and Sync wrapper client around httpx, fastapi, date stuff

Overview

lazyapi

Async and Sync wrapper client around httpx, fastapi, and datetime stuff.


Motivation

This library is forked from an internal project that works with a lot of backend APIs, namely interacting with kubernetes's API. In certain cases, you want to use sync where async isnt suitable, but managing two seperate sync / async client can be annoying, especially when you aren't initializing from async at the start.

This project aims to solve a few problems:

  • Enables both sync and async REST calls from the same client.

  • Improves upon serialization/deserialization over standard json library by using simdjson.

  • Enables dynamic dataclass creation from responses via lazycls that are based on pydantic BaseModel.

  • Work with Timestamp / Datetime much quicker and simpler.

  • Manipulate response objects as efficiently as possible.

  • Wrapper functions for fastapi to enable quick api creation.


Quickstart

pip install --upgrade lazyapi
HttpResponse(resp= , clientType='sync', method='get', timestamp=datetime.datetime(2021, 12, 1, 7, 55, 10, 478544, tzinfo=datetime.timezone.utc)) class HttpResponse(BaseCls): resp: Response clientType: str = 'sync' method: str = 'get' timestamp: str = Field(default_factory=get_timestamp_utc) DefaultHeaders = { 'Accept': 'application/json', 'Content-Type': 'application/json' } --- Client Configs from Env Variables class HttpCfg: timeout = envToFloat('HTTPX_TIMEOUT', 30.0) keep_alive = envToInt('HTTPX_KEEPALIVE', 50) max_connect = envToInt('HTTPX_MAXCONNECT', 200) headers = envToDict('HTTPX_HEADERS', default=DefaultHeaders) class AsyncHttpCfg: timeout = envToFloat('HTTPX_ASYNC_TIMEOUT', 30.0) keep_alive = envToInt('HTTPX_ASYNC_KEEPALIVE', 50) max_connect = envToInt('HTTPX_ASYNC_MAXCONNECT', 200) headers = envToDict('HTTPX_ASYNC_HEADERS', default=DefaultHeaders) """ ">
from lazyapi import APIClient

# Allows initialization of the client from sync call. 
# The client has both async and sync call methods.
apiclient = APIClient(
    base_url = 'https://google.com',
    headers = {},
    module_name = 'customlib',
)

# All requests will be routed through the base_url
# Sync Method
resp = apiclient.get(path='/search?...', **kwargs)

# Async Method
resp = await apiclient.async_get(path='/search?...', **kwargs)

"""
Both yield the same results, only differing in the clientType = sync | async
The underlying classes are auto-generated from Pydantic BaseModels, so anything you can do with Pydantic Models, you can do with these.

> HttpResponse(resp=
    
     , clientType='sync', method='get', timestamp=datetime.datetime(2021, 12, 1, 7, 55, 10, 478544, tzinfo=datetime.timezone.utc))
    

class HttpResponse(BaseCls):
    resp: Response
    clientType: str = 'sync'
    method: str = 'get'
    timestamp: str = Field(default_factory=get_timestamp_utc)

DefaultHeaders = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

---
Client Configs from Env Variables

class HttpCfg:
    timeout = envToFloat('HTTPX_TIMEOUT', 30.0)
    keep_alive = envToInt('HTTPX_KEEPALIVE', 50)
    max_connect = envToInt('HTTPX_MAXCONNECT', 200)
    headers = envToDict('HTTPX_HEADERS', default=DefaultHeaders)

class AsyncHttpCfg:
    timeout = envToFloat('HTTPX_ASYNC_TIMEOUT', 30.0)
    keep_alive = envToInt('HTTPX_ASYNC_KEEPALIVE', 50)
    max_connect = envToInt('HTTPX_ASYNC_MAXCONNECT', 200)
    headers = envToDict('HTTPX_ASYNC_HEADERS', default=DefaultHeaders)

"""

API Specific Features

API Responses

Responses returned from APIClient are of lazyapi.classes.HttpResponse classes which wraps httpx.response in a BaseModel to do response validation, and interfacing with the response such as:

  • .is_error -> bool

  • .is_redirect -> bool

  • .data -> resp.json()

  • .data_obj -> SimdJson.Object / SimdJson.Array

  • .data_cls -> lazycls.LazyCls

  • .timestamp -> str with utc timestamp of request

Time/Datetime Functions

lazyapi.timez: Includes a multitude of datetime based functions to work with timestamp / time / duration.

  • TIMEZONE_DESIRED env to set the desired Timezone Default: America/Chicago

  • TIMEZONE_FORMAT env to set the desired Timezone parse. Default: %Y-%m-%dT%H:%M:%SZ

  • TimezCfg class can be modified based on above two variables.

  • get_timestamp: creates a str based timestamp using local TZ

  • get_timestamp_tz: creates a str based timestamp using the desired TZ

  • get_timestamp_utc: creates a str based timestamp using UTC

  • timer: Simple timer function

  • dtime: Get a datetime object. If no datetime obj is given, returns datetime.now(), otherwise will get the difference

  • get_dtime_secs: converts a datetime object to total num secs.

  • get_dtime_str: Converts a datetime object to a string. If no datetime obj is given, returns datetime.now() converted into desired str format

  • get_dtime_iso: attempts to standardize a datetime obj from existing tz into an iso/desired-formatted datetime

  • dtime_parse: attempts to parse a string, timestamp, etc. into a datetime obj

  • dtime_diff: gets the difference between two datetime objects.

FastAPI wrapper functions

Primarily used to create subapp mounts behind the primary fastapi app.

PlainTextResponse: return PlainTextResponse(content='ok') app.mount('/subapp', subapp) if __name__ == '__main__': import uvicorn uvicorn.run("main:app") """ Now you can expect the route at /subapp/healthz """ ">
from lazyapi import create_fastapi, FastAPICfg

"""
class FastAPICfg:
    app_title = envToStr('FASTAPI_TITLE', 'LazyAPI')
    app_desc = envToStr('FASTAPI_DESC', 'Just a LazyAPI Backend')
    app_version = envToStr('FASTAPI_VERSION', 'v0.0.1')
    include_middleware = envToBool('FASTAPI_MIDDLEWARE', 'true')
    allow_origins = envToList('FASTAPI_ALLOW_ORIGINS', default=["*"])
    allow_methods = envToList('FASTAPI_ALLOW_METHODS', default=["*"])
    allow_headers = envToList('FASTAPI_ALLOW_HEADERS', default=["*"])
    allow_credentials = envToBool('FASTAPI_ALLOW_CREDENTIALS', 'true')

"""
app = create_fastapiapp_name: str, title: str = None, desc: str = None, version: str = None)
subapp = create_fastapi(app_name: 'subapp')

@subapp.get('/healthz')
async def healthcheck() -> PlainTextResponse:
    return PlainTextResponse(content='ok')


app.mount('/subapp', subapp)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app")

"""
Now you can expect the route at
/subapp/healthz


"""
You might also like...
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

 Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions
Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions

Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions To learn more about this project: medium blog post The goal of this proje

REST API with FastAPI and SQLite3.
REST API with FastAPI and SQLite3.

REST API with FastAPI and SQLite3

Example of using FastAPI and MongoDB database.

FastAPI Todo Application Example of using FastAPI and MangoDB database. 💡 Prerequisites Python ⚙️ Build & Run The first thing to do is to clone the r

Basic FastAPI starter with GraphQL, Docker, and MongoDB configurations.

FastAPI + GraphQL Starter A python starter project using FastAPI and GraphQL. This project leverages docker for containerization and provides the scri

FastAPI Learning Example,对应中文视频学习教程:https://space.bilibili.com/396891097

视频教学地址 中文学习教程 1、本教程每一个案例都可以独立跑,前提是安装好依赖包。 2、本教程并未按照官方教程顺序,而是按照实际使用顺序编排。 Video Teaching Address FastAPI Learning Example 1.Each case in this tutorial c

🤪 FastAPI + Vue构建的Mall项目后台管理

Mall项目后台管理 前段时间学习Vue写了一个移动端项目 https://www.charmcode.cn/app/mall/home 然后教程到此就结束了, 我就总感觉少点什么,计划自己着手写一套后台管理。 相关项目 移动端Mall项目源码(Vue构建): https://github.com/

FastAPI on Google Cloud Run

cloudrun-fastapi Boilerplate for running FastAPI on Google Cloud Run with Google Cloud Build for deployment. For all documentation visit the docs fold

FastAPI + Django experiment

django-fastapi-example This is an experiment to demonstrate one potential way of running FastAPI with Django. It won't be actively maintained. If you'

Releases(v0.0.2)
Owner
Chief Architect @ Growth Engine
JSON-RPC server based on fastapi

Description JSON-RPC server based on fastapi: https://fastapi.tiangolo.com Motivation Autogenerated OpenAPI and Swagger (thanks to fastapi) for JSON-R

199 Dec 30, 2022
Generate FastAPI projects for high performance applications

Generate FastAPI projects for high performance applications. Based on MVC architectural pattern, WSGI + ASGI. Includes tests, pipeline, base utilities, Helm chart, and script for bootstrapping local

Radosław Szamszur 274 Jan 08, 2023
Publish Xarray Datasets via a REST API.

Xpublish Publish Xarray Datasets via a REST API. Serverside: Publish a Xarray Dataset through a rest API ds.rest.serve(host="0.0.0.0", port=9000) Clie

xarray-contrib 106 Jan 06, 2023
Python supercharged for the fastai library

Welcome to fastcore Python goodies to make your coding faster, easier, and more maintainable Python is a powerful, dynamic language. Rather than bake

fast.ai 810 Jan 06, 2023
FastAPI Admin Dashboard based on FastAPI and Tortoise ORM.

FastAPI ADMIN 中文文档 Introduction FastAPI-Admin is a admin dashboard based on fastapi and tortoise-orm. FastAPI-Admin provide crud feature out-of-the-bo

long2ice 1.6k Dec 31, 2022
Basic FastAPI starter with GraphQL, Docker, and MongoDB configurations.

FastAPI + GraphQL Starter A python starter project using FastAPI and GraphQL. This project leverages docker for containerization and provides the scri

Cloud Bytes Collection 1 Nov 24, 2022
An extension for GINO to support Starlette server.

gino-starlette Introduction An extension for GINO to support starlette server. Usage The common usage looks like this: from starlette.applications imp

GINO Community 75 Dec 08, 2022
row level security for FastAPI framework

Row Level Permissions for FastAPI While trying out the excellent FastApi framework there was one peace missing for me: an easy, declarative way to def

Holger Frey 315 Dec 25, 2022
EML analyzer is an application to analyze the EML file

EML analyzer EML analyzer is an application to analyze the EML file which can: Analyze headers. Analyze bodies. Extract IOCs (URLs, domains, IP addres

Manabu Niseki 162 Dec 28, 2022
a lightweight web framework based on fastapi

start-fastapi Version 2021, based on FastAPI, an easy-to-use web app developed upon Starlette Framework Version 2020 中文文档 Requirements python 3.6+ (fo

HiKari 71 Dec 30, 2022
FastAPI + Django experiment

django-fastapi-example This is an experiment to demonstrate one potential way of running FastAPI with Django. It won't be actively maintained. If you'

Jordan Eremieff 78 Jan 03, 2023
FastAPI on Google Cloud Run

cloudrun-fastapi Boilerplate for running FastAPI on Google Cloud Run with Google Cloud Build for deployment. For all documentation visit the docs fold

Anthony Corletti 139 Dec 27, 2022
Web Inventory tool, takes screenshots of webpages using Pyppeteer (headless Chrome/Chromium) and provides some extra bells & whistles to make life easier.

WitnessMe WitnessMe is primarily a Web Inventory tool inspired by Eyewitness, its also written to be extensible allowing you to create custom function

byt3bl33d3r 648 Jan 05, 2023
FastAPI framework plugins

Plugins for FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi-plugins FastAPI framework plugins Cache Mem

RES 239 Dec 28, 2022
FastAPI Skeleton App to serve machine learning models production-ready.

FastAPI Model Server Skeleton Serving machine learning models production-ready, fast, easy and secure powered by the great FastAPI by Sebastián Ramíre

268 Jan 01, 2023
Backend logic implementation for realworld with awesome FastAPI

Backend logic implementation for realworld with awesome FastAPI

Nik 2.2k Jan 08, 2023
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 565 Jan 02, 2023
A Prometheus Python client library for asyncio-based applications

aioprometheus aioprometheus is a Prometheus Python client library for asyncio-based applications. It provides metrics collection and serving capabilit

132 Dec 28, 2022
Adds integration of the Jinja template language to FastAPI.

fastapi-jinja Adds integration of the Jinja template language to FastAPI. This is inspired and based off fastapi-chamelon by Mike Kennedy. Check that

Marc Brooks 58 Nov 29, 2022
🤪 FastAPI + Vue构建的Mall项目后台管理

Mall项目后台管理 前段时间学习Vue写了一个移动端项目 https://www.charmcode.cn/app/mall/home 然后教程到此就结束了, 我就总感觉少点什么,计划自己着手写一套后台管理。 相关项目 移动端Mall项目源码(Vue构建): https://github.com/

王小右 131 Jan 01, 2023