hugframeworkpython

Introduction to Hug Framework – Building a Package,API and CLI at once

In this tutorial we will be learning about how to work with a nice framework called Hug. Hug is a framework that allows you to expose a single code in several ways. You can use hug to build some cool products . You can check out how to use hug to productionize your ML models here or on Udemy.

With Hug you can expose your code as

  • A Local Package
  • As An API
  • As A CLI

It does this by using the following decorators respectively

@hug.local()

@hug.get()

@hug.cli()

Let us see how to put it to work.

Installation

You can install hug with pip as below

pip install hug

Exposing Your Code Locally

Hug uses the @hug.local decorator to convert your python functions into a usable package locally.

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

@hug.local()
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 app.py file as a web API with ease by using any of the HTTP methods with the @hug decorator eg @hug.get() or @hug.post() 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.

@hug.get()
@hug.local()
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 app.py

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 .

@hug.cli()
@hug.get('/books')
@hug.local()
def get_books(title:hug.types.text):
	"""Get Books By Title"""
	return {"title":title.upper()}

# For CLI
if __name__ == '__main__':
	get_books.interface.cli()

Hug make it easier to build 3 things from one code base  out of the box.

You can check out the video tutorial here

 

Thanks For Your Time

Jesus Saves

By Jesse E.Agbe(JCharis)

 

2 thoughts on “Introduction to Hug Framework – Building a Package,API and CLI at once”

Leave a Comment

Your email address will not be published. Required fields are marked *