hug
Embrace the APIs of the future. Hug aims to make developing APIs as simple as possible, but no simpler.
Top Related Projects
FastAPI framework, high performance, easy to learn, fast to code, ready for production
The Python micro framework for building web applications.
The little ASGI framework that shines. 🌟
The Web framework for perfectionists with deadlines.
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
The no-magic web API and microservices framework for Python developers, with an emphasis on reliability and performance at scale.
Quick Overview
Hug is a Python framework for building APIs. It aims to make developing APIs as simple as possible, while also ensuring they are fast and modern. Hug supports automatic documentation and versioning, and can be used to create HTTP REST APIs, CLIs, and local Python APIs.
Pros
- Simplifies API development with clean, intuitive syntax
- Automatic API documentation generation
- Supports multiple interfaces (HTTP, CLI, local Python)
- High performance due to Cython compilation
Cons
- Limited community support compared to larger frameworks
- Less flexibility for complex use cases
- Fewer third-party extensions and integrations
- Not as actively maintained as some other API frameworks
Code Examples
- Basic API endpoint:
import hug
@hug.get('/hello')
def hello_world():
return {"message": "Hello World!"}
- API with path parameters:
import hug
@hug.get('/greet/{name}')
def greet(name: hug.types.text):
return {"message": f"Hello, {name}!"}
- API with input validation:
import hug
@hug.post('/user')
def create_user(username: hug.types.text, age: hug.types.number):
return {"username": username, "age": age}
Getting Started
- Install hug:
pip install hug
- Create a file named
api.py
:
import hug
@hug.get('/')
def root():
return {"message": "Welcome to my API!"}
if __name__ == '__main__':
hug.API(__name__).http.serve()
- Run the API:
python api.py
Your API will be available at http://localhost:8000/
.
Competitor Comparisons
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Pros of FastAPI
- Built-in support for asynchronous programming, allowing for high-performance applications
- Extensive automatic API documentation using OpenAPI (Swagger) and JSON Schema
- Strong type hints and data validation using Pydantic models
Cons of FastAPI
- Steeper learning curve for developers new to async programming or type hinting
- Larger dependency footprint compared to Hug's minimal approach
Code Comparison
FastAPI:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Hug:
import hug
@hug.get("/")
def root():
return {"message": "Hello World"}
Both FastAPI and Hug are Python frameworks for building APIs, but they have different approaches and features. FastAPI focuses on modern Python features like type hints and async support, while Hug aims for simplicity and ease of use. FastAPI's automatic documentation and data validation are more comprehensive, but Hug's simpler syntax may be preferable for smaller projects or developers who prioritize minimalism. The code comparison shows that both frameworks have similar basic syntax for defining routes, with FastAPI using async functions by default.
The Python micro framework for building web applications.
Pros of Flask
- Larger ecosystem with extensive third-party extensions
- More mature and battle-tested in production environments
- Greater flexibility for complex applications
Cons of Flask
- More boilerplate code required for basic functionality
- Steeper learning curve for beginners
- Less opinionated, requiring more decision-making from developers
Code Comparison
Flask:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/hello')
def hello():
return jsonify(message='Hello, World!')
Hug:
import hug
@hug.get('/api/hello')
def hello():
return {'message': 'Hello, World!'}
The code comparison shows that Hug requires less boilerplate and provides a more concise syntax for creating API endpoints. Flask, while slightly more verbose, offers more flexibility in how routes and responses are defined.
Both frameworks allow for easy creation of JSON APIs, but Hug's design is more focused on API development, while Flask is a general-purpose web framework that can be adapted for various web development tasks.
The little ASGI framework that shines. 🌟
Pros of Starlette
- More lightweight and flexible, allowing for greater customization
- Better performance and scalability for high-traffic applications
- Active development with frequent updates and improvements
Cons of Starlette
- Steeper learning curve, especially for beginners
- Less opinionated, requiring more setup and configuration
- Fewer built-in features compared to Hug's batteries-included approach
Code Comparison
Hug example:
import hug
@hug.get('/hello/{name}')
def hello(name: hug.types.text):
return {'message': f'Hello {name}!'}
Starlette example:
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
async def hello(request):
name = request.path_params['name']
return JSONResponse({'message': f'Hello {name}!'})
app = Starlette(routes=[
Route('/hello/{name}', hello)
])
Both frameworks offer simple ways to create API endpoints, but Starlette requires more explicit setup. Hug provides a more concise syntax with built-in type checking, while Starlette offers more flexibility in request handling and response generation.
The Web framework for perfectionists with deadlines.
Pros of Django
- Comprehensive full-stack framework with built-in ORM, admin interface, and authentication
- Large ecosystem with extensive third-party packages and plugins
- Robust documentation and large community support
Cons of Django
- Steeper learning curve due to its full-stack nature
- Can be overkill for small, simple projects
- Less flexibility in choosing components compared to microframeworks
Code Comparison
Django:
from django.http import HttpResponse
from django.urls import path
def hello(request):
return HttpResponse("Hello, World!")
urlpatterns = [
path('hello/', hello),
]
Hug:
import hug
@hug.get('/hello')
def hello():
return "Hello, World!"
Django provides a more structured approach with separate URL routing, while Hug offers a simpler, decorator-based API. Django's code is more verbose but provides clear separation of concerns, whereas Hug's code is more concise and straightforward for simple use cases.
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
Pros of Tornado
- Mature and battle-tested framework with a large community and extensive documentation
- Asynchronous networking library that can handle a high number of concurrent connections
- Flexible and customizable, allowing for fine-grained control over request handling
Cons of Tornado
- Steeper learning curve, especially for developers new to asynchronous programming
- More verbose code compared to Hug, requiring more boilerplate for basic functionality
- Less focus on API development specifically, as it's a general-purpose web framework
Code Comparison
Tornado example:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, World!")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
Hug example:
import hug
@hug.get("/")
def hello():
return "Hello, World!"
The Hug example demonstrates its simplicity and focus on API development, while the Tornado example shows its more verbose but flexible approach to request handling.
The no-magic web API and microservices framework for Python developers, with an emphasis on reliability and performance at scale.
Pros of Falcon
- More mature and widely adopted framework with a larger community
- Better performance and scalability for high-load applications
- More extensive documentation and ecosystem support
Cons of Falcon
- Steeper learning curve compared to Hug's simplicity
- Requires more boilerplate code for basic API setup
- Less opinionated, which may lead to more decision-making for developers
Code Comparison
Falcon:
import falcon
class HelloResource:
def on_get(self, req, resp):
resp.media = {"message": "Hello, World!"}
app = falcon.App()
app.add_route('/hello', HelloResource())
Hug:
import hug
@hug.get('/hello')
def hello():
return {"message": "Hello, World!"}
Summary
Falcon is a more robust and performant framework suitable for large-scale applications, while Hug focuses on simplicity and ease of use for rapid API development. Falcon offers better scalability and a larger ecosystem, but requires more setup and has a steeper learning curve. Hug provides a more straightforward approach with less boilerplate, making it ideal for smaller projects or quick prototyping.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Read Latest Documentation - Browse GitHub Code Repository
hug 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 upon Falcon's high performance HTTP library
Supporting hug development
Get professionally supported hug with the Tidelift Subscription
Professional support for hug is available as part of the Tidelift 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 hug
Installing hug is as simple as:
pip3 install hug --upgrade
Ideally, within a virtual environment.
Getting Started
Build an example API with a simple endpoint in just a few lines.
# filename: happy_birthday.py
"""A basic (single function) API written using hug"""
import hug
@hug.get('/happy_birthday')
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 happy_birthday.py
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
Parameters can also be encoded in the URL (check
out happy_birthday.py
for the whole
example).
@hug.get('/greet/{event}')
def greet(event: str):
"""Greets appropriately (from http://blog.ketchum.com/how-to-write-10-common-holiday-greetings/) """
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!"
Versioning with hug
# filename: versioning_example.py
"""A simple example of a hug API call with versioning"""
import hug
@hug.get('/echo', versions=1)
def echo(text):
return text
@hug.get('/echo', versions=range(2, 5))
def echo(text):
return "Echo: {text}".format(**locals())
To run the example:
hug -f versioning_example.py
Then you can access the example from localhost:8000/v1/echo?text=Hi
/ localhost:8000/v2/echo?text=Hi
Or access the documentation for your API from localhost:8000
Note: versioning in hug automatically supports both the version header as well as direct URL based specification.
Testing hug APIs
hug's http
method 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 the hug.test
module:
import hug
import happy_birthday
hug.test.get(happy_birthday, 'happy_birthday', {'name': 'Timothy', 'age': 25}) # Returns a Response object
You can use this Response
object for test assertions (check
out test_happy_birthday.py
):
def tests_happy_birthday():
response = hug.test.get(happy_birthday, 'happy_birthday', {'name': 'Timothy', 'age': 25})
assert response.status == HTTP_200
assert response.data is not None
Running hug with other WSGI based servers
hug 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 to module_name
: __hug_wsgi__
.
For Example:
uwsgi --http 0.0.0.0:8000 --wsgi-file examples/hello_world.py --callable __hug_wsgi__
To run the hello world hug example API.
Building Blocks of a hug API
When building an API using the hug framework you'll use the following concepts:
METHOD Decorators get
, 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 decorator
def hello_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 Annotations functions that optionally are attached to your methods arguments to specify how the argument is validated and converted into a Python type
@hug.get()
def math(number_1:int, number_2:int): #The :int after both arguments is the Type Annotation
return number_1 + number_2
Type annotations also feed into hug
's automatic documentation
generation to let users of your API know what data to supply.
Directives functions 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()
def test_time(hug_timer):
return {'time_taken': float(hug_timer)}
Directives may be accessed via an argument with a hug_
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()
def square(value=1, **kwargs):
'''Returns passed in parameter multiplied by itself'''
return value * value
@hug.get()
@hug.local()
def tester(value: square=10):
return value
tester() == 100
For completeness, here is an example of accessing the directive via the magic name approach:
@hug.directive()
def multiply(value=1, **kwargs):
'''Returns passed in parameter multiplied by itself'''
return value * value
@hug.get()
@hug.local()
def tester(hug_multiply=10):
return hug_multiply
tester() == 100
Output Formatters a function that takes the output of your API function and formats it for transport to the user of the API.
@hug.default_output_format()
def my_output_formatter(data):
return "STRING:{0}".format(data)
@hug.get(output=hug.output_format.json)
def hello():
return {'hello': 'world'}
as shown, you can easily change the output format for both an entire API as well as an individual API call
Input Formatters a 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")
def my_input_formatter(data):
return ('Results', hug.input_format.json(data))
Input formatters are mapped based on the content_type
of the request data, and only perform basic parsing. More detailed parsing should be done by the Type Annotations present on your api_function
Middleware functions that get called for every request a hug API processes
@hug.request_middleware()
def process_data(request, response):
request.env['SERVER_NAME'] = 'changed'
@hug.response_middleware()
def process_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 mapping can be used to override inferred parameter names, eg. for reserved keywords:
import marshmallow.fields as fields
...
@hug.get('/foo', map_params={'from': 'from_date'}) # API call uses 'from'
def get_foo_by_date(from_date: fields.DateTime()):
return find_foo(from_date)
Input formatters are mapped based on the content_type
of the request data, and only perform basic parsing. More detailed parsing should be done by the Type Annotations present on your api_function
Splitting APIs over multiple files
hug 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.py
import hug
@hug.get('/')
def say_hi():
return 'hello from something'
Can be imported into the main API file:
__init__.py
import hug
from . import something
@hug.get('/')
def say_hi():
return "Hi from root"
@hug.extend_api('/something')
def something_api():
return [something]
Or alternatively - for cases like this - where only one module is being included per a URL route:
#alternatively
hug.API(__name__).extend(something, '/something')
Configuring hug 404
By 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 404
Additionally, you can easily create a custom 404 handler using the hug.not_found
decorator:
@hug.not_found()
def not_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)
def not_found_handler():
return ""
@hug.not_found(versions=2)
def not_found_handler():
return "Not Found"
Asyncio support
When using the get
and cli
method decorator on coroutines, hug will schedule
the execution of the coroutine.
Using asyncio coroutine decorator
@hug.get()
@asyncio.coroutine
def hello_world():
return "Hello"
Using Python 3.5 async keyword.
@hug.get()
async def hello_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 Docker
If you like to develop in Docker and keep your system clean, you can do that but you'll need to first install Docker Compose.
Once you've done that, you'll need to cd
into the docker
directory 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-compose up gunicorn
# From the host machine, find your Dockers IP address.
# For Windows & Mac:
$ docker-machine ip default
# For Linux:
$ ifconfig docker0 | grep 'inet' | cut -d: -f2 | awk '{ print $1}' | head -n1
By default, the IP is 172.17.0.1. Assuming that's the IP you see, as well, you would then go to http://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-compose run workspace bash
On your Docker workspace
container, the ./docker/templates
directory on your host computer is mounted to /src
in the Docker container. This is specified under services
> app
of ./docker/docker-compose.yml
.
bash-4.3# cd /src
bash-4.3# tree
.
âââ __init__.py
âââ handlers
âââ birthday.py
âââ hello.py
1 directory, 3 files
Security contact information
hug 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 the Tidelift 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 find this hug helpful as you develop your next Python API!
~Timothy Crosley
Top Related Projects
FastAPI framework, high performance, easy to learn, fast to code, ready for production
The Python micro framework for building web applications.
The little ASGI framework that shines. 🌟
The Web framework for perfectionists with deadlines.
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
The no-magic web API and microservices framework for Python developers, with an emphasis on reliability and performance at scale.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot