Package: esmerald
Esmerald🚀 Highly scalable, performant, easy to learn, easy to code and for every application. 🚀Documentation:https://esmerald.dev📚Source Code:https://github.com/dymmond/esmeraldThe official supported version is always the latest released.Esmerald is a modern, powerful, flexible, high performant, web framework designed to build not only APIs
but also full scalable applications from the smallest to enterprise level.Esmerald is designed to build with python 3.8+ and based on standard python type hints and on the top of
the heavily knownStarletteandPydantic/msgspec.Check out theEsmerald documentation 📚The official supported version is always the latest released.MotivationThere are great frameworks out there like FastAPI, Starlite, Flama, Flask, Django... All of them solving majority
of the current day-to-day problems of 99% of the applications but leaving the 1% that is usually around structure
and design/business without to much to do.Esmerald got the inspiration from those great frameworks out there and was built with all the known amazing
features but with business in mind as well. Starlite, for example, gave the inspiration for the transformers and for the Signature models,
something very useful that helped Esmerald integerating with pydantic.
FastAPI gave the inspiration for API designing, Django for the permissions, Flask for the simplicity, NestJS for the
controllers and the list goes on.For a job to be done properly, usually it is never done alone and there is always a driver and inspiration to it.Requirementspython 3.8+Esmerald wouldn't be possible without two colossals:StarlettePydanticInstallation$pipinstallesmeraldAn ASGI server is also needed to run in production, we recommendUvicornbut it is entirely
up to you.$pipinstalluvicornIf you want install esmerald with specifics:Support for template system such as jinja2 and mako:$pipinstallesmerald[templates]Support for the internal scheduler:$pipinstallesmerald[schedulers]Support for the jwt used internally by Esmerald:$pipinstallesmerald[jwt]Support for ORJSON and UJSON:$pipinstallesmerald[encoders]If you want to use the esmerald testing client:$pipinstallesmerald[test]If you want to use the esmerald shell:Moredetailsabout this topicin the docs$pipinstallesmerald[ipython]# default shell$pipinstallesmerald[ptpython]# ptpython shellStart a project using directives!!! Warning
This is for more advanced users that are already comfortable with Esmerald (or Python in general)
or feel like it is not a problem using these directives. If you do not feel comfortable yet to use this,
please continue reading the documentation and learning more about Esmerald.If you wish to start an Esmerald project with a default suggested structure.esmeraldcreateproject<YOUR-PROJECT-NAME>This will generate a scaffold for your project with some pre-defined files in a simple fashion.
This will also generate a file for the tests using the EsmeraldTestClient, so make sure you run:$pipinstallesmerald[test]Or you can skip this step if you don't want to use the EsmeraldTestClient.You can findmore informationabout this directive and how to
use it.Key FeaturesFluid and Fast: Thanks to Starlette and Pydantic/msgspec.Fast to develop: Thanks to the simplicity of design, the development times can be reduced exponentially.Intuitive: If you are used to the other frameworks, Esmerald is a no brainer to develop.Easy: Developed with design in mind and easy learning.Short: With the OOP available natively there is no need for code duplication. SOLID.Ready: Get your application up and running with production-ready code.OOP and Functional: Design APIs in any desired way. OOP or Functional is available.Async and Sync: Do you prefer sync or async? You can have both.Middleware: Apply middlewares on the application level or API level.Exception Handlers: Apply exception handlers on any desired level.Permissions: Apply specific rules and permissions on each API.Interceptors: Intercept requests and add logic before reaching the endpoint.Pluggables: Create plugins for Esmerald and hook them into any application and/or
distribute them.DAO and AsyncDAO: Avoid database calls directly from the APIs. Use business objects instead.ORM Support: Native support forSaffierandEdgy.ODM Support: Native support forMongoz.APIView: Class Based endpoints for your beloved OOP design.JSON serialization/deserialization: Both UJSON and ORJON support.Lifespan: Support for the newly lifespan and on_start/on_shutdown events.Scheduler: Yes, that's right, it comes with a scheduler for those automated tasks.Dependency Injection: Like any other great framework out there.Simplicity from settings: Yes, we have a way to make the code even cleaner by introducing settings
based systems.msgspec- Support formsgspec.Relation to Starlette and other frameworksEsmerald uses Starlette under the hood. The reason behind this decison comes with the fact that performance is there
and no issues with routing.Once the application is up, all the routes are mounted and therefore the url paths are defined.
Esmerald encourages standard practices and design in mind which means that any application, big or small,
custom or enterprise, fits within Esmerald ecosystem without scalability issues.SettingsLike every other framework, when starting an application, a lot ofsettingscan/need to be
passed to the main object and this can be very dauting and hugly to maintain and see.Esmerald comes with thesettingsin mind. A set of defaults that can be overridden by your very own settings
module but not limited to it as you can still use the classic approach of passing everything into a
Esmerald instance directly when instantiating.Example of classic approach:fromexampleimportExampleObject# ExampleObject is an instance of another application# and it serves only for exampleapp=ExampleObject(setting_one=...,setting_two=...,setting_three=...)Inspired by the greatDjangoand using pydantic, Esmerald has a default object
ready to be used out-of-the-box.Esmerald:fromesmeraldimportEsmeraldapp=Esmerald()And that's it! All the default settings are loaded! This is simple of course but can you override
inside the object as well? Yes!fromesmeraldimportEsmeraldapp=Esmerald(app_name='My App',title='My title')Same as the classics.So how does Esmerald know about the default settings? EntersEsmerald settings module.Esmerald Settings ModuleThis is the way Esmerald defaults the values. When starting an application, the system looks for aESMERALD_SETTINGS_MODULEenvironment variable. If no variable is supplied then the system will default toEsmeraldAPISettingssettings and start.Custom SettingsSeparation of settings by enviromment is a must have these days and starting with default of Esmerald will not be
enough for any application.The settings are pydantic standard settings and therefore compatible with Esmerald.
The system brings some defaults that can be used out-of-the-box but it's not mandatory to be used.
The environment defaults toproduction.fromesmeraldimportEsmeraldAPISettingsfromesmerald.conf.enumsimportEnvironmentTypeclassDevelopment(EsmeraldAPISettings):app_name:bool='My app in dev'environment:str=EnvironmentType.DEVELOPMENTLoad the settings into your Esmerald application:Assuming your Esmerald app is inside ansrc/app.py.ESMERALD_SETTINGS_MODULE='myapp.settings.Development' python -m src.app.pyGateway, WebSocketGateway and IncludeStarlette offers the Route classes for simple path assignments but this is also very limiting if something more
complex in mind. Esmerald extends that functionality and adds someflairand levels up by having the
Gateway, WebSocketGateway and Include.Those are special objects that allow all the magic of Esmerald to happen.For a classic, direct, one file single approach.In a nutshell:fromesmeraldimportEsmerald,get,status,Request,UJSONResponse,Gateway,WebSocketGateway,Websocket@get(status_code=status.HTTP_200_OK)asyncdefhome()->UJSONResponse:returnUJSONResponse({"detail":"Hello world"})@get()asyncdefanother(request:Request)->dict:return{"detail":"Another world!"}@websocket(path="/{path_param:str}")asyncdefworld_socket(socket:Websocket)->None:awaitsocket.accept()msg=awaitsocket.receive_json()assertmsgassertsocketawaitsocket.close()app=Esmerald(routes=[Gateway(handler=home),Gateway(handler=another),WebSocketGateway(handler=world_socket),])Design in mindGood design is always encouraged and Esmerald allows complex routing on any level.The handlers (views)fromesmeraldimportget,post,put,status,websocket,APIView,Request,JSONResponse,Response,WebSocketfrompydanticimportBaseModelclassProduct(BaseModel):name:strsku:strprice:float@put('/product/{product_id}')defupdate_product(product_id:int,data:Product)->dict:return{"product_id":product_id,"product_name":product.name}@get(status_code=status.HTTP_200_OK)asyncdefhome()->JSONResponse:returnJSONResponse({"detail":"Hello world"})@get()asyncdefanother(request:Request)->dict:return{"detail":"Another world!"}@websocket(path="/{path_param:str}")asyncdefworld_socket(socket:Websocket)->None:awaitsocket.accept()msg=awaitsocket.receive_json()assertmsgassertsocketawaitsocket.close()classWorld(APIView):@get(path='/{url}')asyncdefhome(request:Request,url:str)->Response:returnResponse(f"URL:{url}")@post(path='/{url}',status_code=status.HTTP_201_CREATED)asyncdefmars(request:Request,url:str)->JSONResponse:...@websocket(path="/{path_param:str}")asyncdefpluto(self,socket:Websocket)->None:awaitsocket.accept()msg=awaitsocket.receive_json()assertmsgassertsocketawaitsocket.close()If apathis not provided, defaults to/.The gateways (urls)fromesmeraldimportGateway,WebSocketGatewayfrom.viewsimporthome,another,world_socket,Worldroute_patterns=[Gateway(handler=update_product),Gateway(handler=home),Gateway(handler=another),Gateway(handler=World),WebSocketGateway(handler=world_socket),]If apathis not provided, defaults to/.The IncludeThis is a very special object that allows the import of any route from anywhere in the application.Includeaccepts the import vianamespaceor viarouteslist but not both.When using anamespace, theIncludewill look for the defaultroute_patternsobject list in the imported
namespace unless a differentpatternis specified.The pattern only works if the imports are done vianamespaceand not viaroutes.Importing using namespace:fromesmeraldimportIncluderoute_patterns=[Include(namespace='myapp.accounts.urls')]Importing using routes:fromesmeraldimportIncludefrommyapp.accountsimporturlsroute_patterns=[Include(routes=urls.route_patterns)]If apathis not provided, defaults to/.Using a different patternfromesmeraldimportGateway,WebSocketGatewayfrom.viewsimporthome,another,world_socket,Worldmy_urls=[Gateway(handler=update_product),Gateway(handler=home),Gateway(handler=another),Gateway(handler=World),WebSocketGateway(handler=world_socket),]Importing using namespace:fromesmeraldimportIncluderoute_patterns=[Include(namespace='myapp.accounts.urls',pattern='my_urls')]Include and EsmeraldTheIncludecan be very helpful mostly when the goal is to avoid a lot of imports and massive list
of objects to be passed into one single object. This can be particulary useful to make a Esmerald instance.Example:fromesmeraldimportIncluderoute_patterns=[Include(namespace='myapp.accounts.urls',pattern='my_urls')]fromesmeraldimportEsmerald,Includeapp=Esmerald(routes=[Include('src.urls')])Run the applicationAs mentioned before, we recomment uvicorn for production but it's not mandatory.Using uvicorn:uvicornsrc:app--reload

INFO:Uvicornrunningonhttp://127.0.0.1:8000(PressCTRL+Ctoquit)INFO:Startedreloaderprocess[28720]INFO:Startedserverprocess[28722]INFO:Waitingforapplicationstartup.
INFO:Applicationstartupcomplete.Run the application with custom settingsUsing uvicorn:ESMERALD_SETTINGS_MODULE=myapp.AppSettingsuvicornsrc:app--reload

INFO:Uvicornrunningonhttp://127.0.0.1:8000(PressCTRL+Ctoquit)INFO:Startedreloaderprocess[28720]INFO:Startedserverprocess[28722]INFO:Waitingforapplicationstartup.
INFO:Applicationstartupcomplete.OpenAPI documentationEsmerald also comes with OpenAPI docs integrated. For those used to that, this is roughly the same and to make it
happen, there were inspirations that helped Esmerald getting there fast.Esmerald starts automatically the OpenAPI documentation by injecting the OpenAPIConfig default from
the settings and makes Swagger, ReDoc an Stoplight elements available to you out of the box.To access the OpenAPI, simply start your local development and access:Swagger-/docs/swagger.Redoc-/docs/redoc.Stoplight Elements-/docs/elements.There are more details abouthow to configure the OpenAPIConfigwithin the documentation.There is also a good explanation on how to use theOpenAPIResponseas well.NotesThis is just a very high-level demonstration of how to start quickly and what Esmerald can do.
There are plenty more things you can do with Esmerald. Enjoy! 😊SponsorsCurrently there are no sponsors of Esmerald but you can financially help and support the author thoughGitHub sponsorsand become aSpecial oneor aLegend.