HUG Framework Python

HUG Framework Python

I know from the name it sounds funny HUG, HUH! : )

HUG simply stands for Hopefully Useful Guide.

With Hug, you can expose your code as

  1.  A Local Package 
  2.  An API
  3.  A CLI
It does this by using the following decorators respectively




You can install hug with pip as below

pip install hug

Getting Started

Build an example API with a simple endpoint in just a few lines.

# filename:
"""A basic (single function) API written using hug"""
import hug

def happy_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 -f

You can access the example in your browser at localhost:8000/happy_birthday?name=hug&age=1. Then check out the documentation for your API at localhost:8000/documentation

def greet(event: str):
    """Greets appropriately (from  """
    greetings = "Happy"
    if event == "Christmas":
        greetings = "Merry"
    if event == "Kwanzaa":
        greetings = "Joyous"
    if event == "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!"

Let us create a file called  And then place in the following code.

def get_books(title:hug.types.text):
"""Get Books By Title"""
return {"title":title.upper()}

To use it you just have to import it like you do every package

from app import get_books

With the usage of the @hug.local() decorator, you can be able to use this same function locally like a package.

Exposing Your Code as a Web Application Programming Interface (API)

Hug allows you to also expose the above code in our file as a web API with ease by using any of the HTTP methods with the @hug decorator eg @hug.get() or respectively for GET and POST methods.

Hence in our case, we will just add the decorator on top of our function and run the script using the hug CLI in your terminal.

def get_books(title:hug.types.text):
"""Get Books By Title"""
return {"title":title.upper()}

Then in our terminal, you can run it as

hug -f

This will spin up a web API on the localhost:8000 that you can view in your browser or REST Client.

Exposing Your Code as A Command Line Interface (CLI)

Finally, you can also expose your code as a CLI using the @hug.cli() decorator.

def get_books(title:hug.types.text):
"""Get Books By Title"""
return {"title":title.upper()}

# For CLI
if __name__ == '__main__':
Hug make it easier to build 3 things from one code base out of the box.

   This article is written by Rohit Bansal Intern at CPPSECRETS