Package: natsapi
NatsAPITable of ContentsInstallationUsageDocsExamplesBasicError handling with sentryReloadGenerating documentation (asyncapi)PluginsHistoryNatsAPI is a framework to develop Python3 applications that usesnatsas communication medium instead of http. With nats you have a smaller footprint, faster req/s, pub/sub and better observability.
It is highly inspired byFastAPIand has the same development style. NatsAPI produces anAsyncAPIschema out of the box,this schema is not fully compatible with the standard.Installation$ pip install natsapiUsageDocsUNDER CONSTRUCTIONExamplesBasicfromnatsapiimportNatsAPI,SubjectRouterfrompydanticimportBaseModelclassMessage(BaseModel):message:strclassPerson(BaseModel):first_name:strlast_name:strapp=NatsAPI("natsapi")router=SubjectRouter()@router.request("persons.greet",result=Message)asyncdefgreet_person(app:NatsAPI,person:Person):return{"message":f"Greetings{person.first_name}{person.last_name}!"}app.include_router(router)if__name__=="__main__":app.run()Run as follows:$pythonapp.pyDocs will be rendered as:Send a request:fromnatsapiimportNatsAPIimportasyncioasyncdefmain():app=awaitNatsAPI("client").startup()params={"person":{"first_name":"Foo","last_name":"Bar"}}r=awaitapp.nc.request("natsapi.persons.greet",params=params,timeout=5)print(r.result)asyncio.run(main())#> {'message': 'Greetings Foo Bar!'}or on the command line$natsrequestnatsapi.persons.greet'{"params": {"person": {"first_name": "Foo", "last_name": "Bar"}}}'18:19:00Sendingrequeston"natsapi.persons.greet"18:19:00Receivedon"_INBOX.dpBgTyG9XC5NhagdqRHTcp.eMkVkru8"rtt1.052463ms{"jsonrpc":"2.0","id":"c2bc2d20-dbd5-4e39-a22d-c22a8631c5a3","result":{"message":"Greetings Foo Bar!"},"error":null}Error handling with sentryfromnatsapiimportNatsAPI,SubjectRouterimportloggingfrompydanticimportValidationErrorfromsentry_sdkimportconfigure_scopefromnatsapi.modelsimportJsonRPCRequest,JsonRPCErrorfrompydanticimportBaseModelclassStatusResult(BaseModel):status:strapp=NatsAPI("natsapi-example")router=SubjectRouter()@router.request("healthz",result=StatusResult)asyncdefhandle_user(app:NatsAPI):return{"status":"OK"}app.include_router(router)defconfigure_sentry(auth):withconfigure_scope()asscope:scope.user={"email":auth.get("email"),"id":auth.get("uid"),"ip_address":auth.get("ip_address"),}@app.exception_handler(ValidationError)asyncdefhandle_validation_exception(exc:ValidationError,request:JsonRPCRequest,subject:str)->JsonRPCError:auth=request.params.get("auth")or{}configure_sentry(auth)logging.error(exc,exc_info=True,stack_info=True,extra={"auth":auth,"json":request.dict(),"subject":subject,"NATS":True,"code":-32003},)returnJsonRPCError(code=-90001,message="VALIDATION_ERROR",data={"error_str":str(exc)})if__name__=="__main__":app.run(reload=False)ReloadWhen running from a file you can add a reload flag (hot-reload on file change) or use theNATSAPI_RELOADenv var.if __name__ == "__main__":
    app.run(reload=True)Generating documentation (asyncapi)To see the documentation, you can use the binary to run the server. Root path isnatsapi-exampleso:$./nats-redoc4222master.trinity-testing

Serverrunning
Docscanbefoundonlocalhost:8090
connectedtonatsonport4222When surfing tolocalhost:8090, the documentation should look like this:PluginsPlugins can be added and are found innatsapi/plugin.py.natsapi_mock: A handy mock fixture to intercept nats requests and to fake nats responses for any subject.