Package: hug
Read Latest Documentation-Browse GitHub Code Repositoryhug aims to make developing Python driven APIs as simple as possible, but no simpler. As a result, it drastically simplifies Python API development.hug's Design Objectives:Make developing a Python driven API as succinct as a written definition.The framework should encourage code that self-documents.It should be fast. A developer should never feel the need to look somewhere else for performance reasons.Writing tests for APIs written on-top of hug should be easy and intuitive.Magic done once, in an API framework, is better than pushing the problem set to the user of the API framework.Be the basis for next generation Python APIs, embracing the latest technology.As a result of these goals, hug is Python 3+ only and built uponFalcon'shigh performance HTTP librarySupporting hug developmentGet professionally supported hug with the Tidelift SubscriptionProfessional support for hug is available as part of theTidelift
Subscription.
Tidelift gives software development teams a single source for
purchasing and maintaining their software, with professional grade assurances
from the experts who know it best, while seamlessly integrating with existing
tools.Installing hugInstalling hug is as simple as:pip3installhug--upgradeIdeally, within avirtual environment.Getting StartedBuild an example API with a simple endpoint in just a few lines.# filename: happy_birthday.py"""A basic (single function) API written using hug"""importhug@hug.get('/happy_birthday')defhappy_birthday(name,age:hug.types.number=1):"""Says happy birthday to a user"""return"Happy{age}Birthday{name}!".format(**locals())To run, from the command line type:hug-fhappy_birthday.pyYou can access the example in your browser at:localhost:8000/happy_birthday?name=hug&age=1. Then check out the
documentation for your API atlocalhost:8000/documentationParameters can also be encoded in the URL (check
outhappy_birthday.pyfor the whole
example).@hug.get('/greet/{event}')defgreet(event:str):"""Greets appropriately (from http://blog.ketchum.com/how-to-write-10-common-holiday-greetings/)  """greetings="Happy"ifevent=="Christmas":greetings="Merry"ifevent=="Kwanzaa":greetings="Joyous"ifevent=="wishes":greetings="Warm"return"{greetings}{event}!".format(**locals())Which, once you are running the server as above, you can use this way:curl http://localhost:8000/greet/wishes
"Warm wishes!"Versioning with hug# filename: versioning_example.py"""A simple example of a hug API call with versioning"""importhug@hug.get('/echo',versions=1)defecho(text):returntext@hug.get('/echo',versions=range(2,5))defecho(text):return"Echo:{text}".format(**locals())To run the example:hug-fversioning_example.pyThen you can access the example fromlocalhost:8000/v1/echo?text=Hi/localhost:8000/v2/echo?text=HiOr access the documentation for your API fromlocalhost:8000Note: versioning in hug automatically supports both the version header as well as direct URL based specification.Testing hug APIshug'shttpmethod decorators don't modify your original functions. This makes testing hug APIs as simple as testing any other Python functions. Additionally, this means interacting with your API functions in other Python code is as straight forward as calling Python only API functions. hug makes it easy to test the full Python stack of your API by using thehug.testmodule:importhugimporthappy_birthdayhug.test.get(happy_birthday,'happy_birthday',{'name':'Timothy','age':25})# Returns a Response objectYou can use thisResponseobject for test assertions (check
outtest_happy_birthday.py):deftests_happy_birthday():response=hug.test.get(happy_birthday,'happy_birthday',{'name':'Timothy','age':25})assertresponse.status==HTTP_200assertresponse.dataisnotNoneRunning hug with other WSGI based servershug exposes a__hug_wsgi__magic method on every API module automatically. Running your hug based API on any standard wsgi server should be as simple as pointing it tomodule_name:__hug_wsgi__.For Example:uwsgi--http0.0.0.0:8000--wsgi-fileexamples/hello_world.py--callable__hug_wsgi__To run the hello world hug example API.Building Blocks of a hug APIWhen building an API using the hug framework you'll use the following concepts:METHOD Decoratorsget,post,update, etc HTTP method decorators that expose your Python function as an API while keeping your Python method unchanged@hug.get()# <- Is the hug METHOD decoratordefhello_world():return"Hello"hug uses the structure of the function you decorate to automatically generate documentation for users of your API. hug always passes a request, response, and api_version variable to your function if they are defined params in your function definition.Type Annotationsfunctions that optionally are attached to your methods arguments to specify how the argument is validated and converted into a Python type@hug.get()defmath(number_1:int,number_2:int):#The :int after both arguments is the Type Annotationreturnnumber_1+number_2Type annotations also feed intohug's automatic documentation
generation to let users of your API know what data to supply.Directivesfunctions that get executed with the request / response data based on being requested as an argument in your api_function.
These apply as input parameters only, and can not be applied currently as output formats or transformations.@hug.get()deftest_time(hug_timer):return{'time_taken':float(hug_timer)}Directives may be accessed via an argument with ahug_prefix, or by using Python 3 type annotations. The latter is the more modern approach, and is recommended. Directives declared in a module can be accessed by using their fully qualified name as the type annotation (ex:module.directive_name).Aside from the obvious input transformation use case, directives can be used to pipe data into your API functions, even if they are not present in the request query string, POST body, etc. For an example of how to use directives in this way, see the authentication example in the examples folder.Adding your own directives is straight forward:@hug.directive()defsquare(value=1,**kwargs):'''Returns passed in parameter multiplied by itself'''returnvalue*value@hug.get()@hug.local()deftester(value:square=10):returnvaluetester()==100For completeness, here is an example of accessing the directive via the magic name approach:@hug.directive()defmultiply(value=1,**kwargs):'''Returns passed in parameter multiplied by itself'''returnvalue*value@hug.get()@hug.local()deftester(hug_multiply=10):returnhug_multiplytester()==100Output Formattersa function that takes the output of your API function and formats it for transport to the user of the API.@hug.default_output_format()defmy_output_formatter(data):return"STRING:{0}".format(data)@hug.get(output=hug.output_format.json)defhello():return{'hello':'world'}as shown, you can easily change the output format for both an entire API as well as an individual API callInput Formattersa function that takes the body of data given from a user of your API and formats it for handling.@hug.default_input_format("application/json")defmy_input_formatter(data):return('Results',hug.input_format.json(data))Input formatters are mapped based on thecontent_typeof the request data, and only perform basic parsing. More detailed parsing should be done by the Type Annotations present on yourapi_functionMiddlewarefunctions that get called for every request a hug API processes@hug.request_middleware()defprocess_data(request,response):request.env['SERVER_NAME']='changed'@hug.response_middleware()defprocess_data(request,response,resource):response.set_header('MyHeader','Value')You can also easily add any Falcon style middleware using:__hug__.http.add_middleware(MiddlewareObject())Parameter mappingcan be used to override inferred parameter names, eg. for reserved keywords:importmarshmallow.fieldsasfields...@hug.get('/foo',map_params={'from':'from_date'})# API call uses 'from'defget_foo_by_date(from_date:fields.DateTime()):returnfind_foo(from_date)Input formatters are mapped based on thecontent_typeof the request data, and only perform basic parsing. More detailed parsing should be done by the Type Annotations present on yourapi_functionSplitting APIs over multiple fileshug enables you to organize large projects in any manner you see fit. You can import any module that contains hug decorated functions (request handling, directives, type handlers, etc) and extend your base API with that module.For example:something.pyimporthug@hug.get('/')defsay_hi():return'hello from something'Can be imported into the main API file:__init__.pyimporthugfrom.importsomething@hug.get('/')defsay_hi():return"Hi from root"@hug.extend_api('/something')defsomething_api():return[something]Or alternatively - for cases like this - where only one module is being included per a URL route:#alternativelyhug.API(__name__).extend(something,'/something')Configuring hug 404By default, hug returns an auto generated API spec when a user tries to access an endpoint that isn't defined. If you would not like to return this spec you can turn off 404 documentation:From the command line application:hug-nd-f{file}#nd flag tells hug not to generate documentation on 404Additionally, you can easily create a custom 404 handler using thehug.not_founddecorator:@hug.not_found()defnot_found_handler():return"Not Found"This decorator works in the same manner as the hug HTTP method decorators, and is even version aware:@hug.not_found(versions=1)defnot_found_handler():return""@hug.not_found(versions=2)defnot_found_handler():return"Not Found"Asyncio supportWhen using thegetandclimethod decorator on coroutines, hug will schedule
the execution of the coroutine.Using asyncio coroutine decorator@hug.get()@asyncio.coroutinedefhello_world():return"Hello"Using Python 3.5 async keyword.@hug.get()asyncdefhello_world():return"Hello"NOTE: Hug is running on top Falcon which is not an asynchronous server. Even if using
asyncio, requests will still be processed synchronously.Using DockerIf you like to develop in Docker and keep your system clean, you can do that but you'll need to first installDocker Compose.Once you've done that, you'll need tocdinto thedockerdirectory and run the web server (Gunicorn) specified in./docker/gunicorn/Dockerfile, after which you can preview the output of your API in the browser on your host machine.$cd./docker# This will run Gunicorn on port 8000 of the Docker container.$docker-composeupgunicorn# From the host machine, find your Dockers IP address.# For Windows & Mac:$docker-machineipdefault# For Linux:$ifconfigdocker0|grep'inet'|cut-d:-f2|awk'{ print $1}'|head-n1By default, the IP is 172.17.0.1. Assuming that's the IP you see, as well, you would then go tohttp://172.17.0.1:8000/in your browser to view your API.You can also log into a Docker container that you can consider your work space. This workspace has Python and Pip installed so you can use those tools within Docker. If you need to test the CLI interface, for example, you would use this.$docker-composerunworkspacebashOn your Dockerworkspacecontainer, the./docker/templatesdirectory on your host computer is mounted to/srcin the Docker container. This is specified underservices>appof./docker/docker-compose.yml.bash-4.3#cd/src
bash-4.3#tree
.
├──__init__.py
└──handlers├──birthday.py└──hello.py1directory,3filesSecurity contact informationhug takes security and quality seriously. This focus is why we depend only on thoroughly tested components and utilize static analysis tools (such as bandit and safety) to verify the security of our code base.
If you find or encounter any potential security issues, please let us know right away so we can resolve them.To report a security vulnerability, please use theTidelift security contact.
Tidelift will coordinate the fix and disclosure.Why hug?HUG simply stands for Hopefully Useful Guide. This represents the project's goal to help guide developers into creating well written and intuitive APIs.Thanks and I hope you findthishug helpful as you develop your next Python API!~Timothy Crosley