SlideShare a Scribd company logo
the easiest API for your apps
with hug
1
Mocking services
● static (no logic allowed)
● limited
● essential functions are for paid users only
● no full control over API
2
hug
● written by Timothy Crosley
● currently on version 2.1.2
● runs on python3
● built on top of Falcon
● magic done once
● feature-filled
● as easy as writing definition
3
source: http://www.hug.rest
bare minimum
4
# server.py
import hug
@hug.get()
def hello():
return 'Hi there!'
$ hug -f server.py
run it with
live demo
5
code included in
the demo
6
'''Funny cat names in hug'''
import hug
cats = []
#starts up on server launch
@hug.startup()
def init(api):
cats.extend(['fluffy','bubba','cuddles','meowly'])
#default arguments make them not required
@hug.get()
def hello(name :hug.types.text='stranger'):
'''Greets you on /v1/hello'''
return 'Hi there ' + name + '!'
#supports all http methods
@hug.post('/cats')
def add_cat(name :hug.types.text):
'''Add cat name to the list'''
cats.append(name)
return {'result':'ok'}
#easy versioning
@hug.post('/cats', versions=2)
def add_cat(name :hug.types.text):
'''Add cat name to the list'''
cats.append(name)
return {'id':len(cats)-1}
#supports URI params
@hug.get('/cats/{id}')
def get_cat(id :hug.types.number):
'''Get cat name with specified id'''
return cats[id]
#provide examples for easy launch from
documentation
@hug.get('/cats', examples='length=3')
def get_cats(length :hug.types.number=None):
'''Get funny cat names'''
if length:
return cats[:length]
else:
return cats
features supported by hug
7
types
● used for validation or
simple mutation of
parameters
● work through function
annotations
● various different types
available and custom
types are supported
8
★ primitive types(text, number, boolean etc.)
★ delimited list
★ multiple types at once
★ more than, less than, length
★ cut off
types
● used for validation or
simple mutation of
parameters
● work through function
annotations
● various different types
available and custom
types are supported
9
@hug.type(extend=hug.types.text)
def htmlcolor(value):
'''HTML color code'''
pattern = re.compile('#[0-9a-fA-F]{6}')
m = pattern.match(value)
if m:
return m.group()
else:
raise ValueError('Value is not a html color code')
@hug.post('/lamp/{id}/changecolor')
def change_color(id :hug.types.number, color :htmlcolor()):
return {'id':id,'color':color}
@hug.type(extend=htmlcolor)
def torgbtuple(value):
'''Color tuple'''
value = value.lstrip('#')
return tuple(int(value[i:i + 2],16) for i in range(0, 6, 2))
@hug.post('/color')
def get_rgb_touple(color :torgbtuple()):
return {'red':color[0],'green':color[1],'blue':color[2]}
directives
● work as prefixed
arguments or function
annotations
● can provide pretty
much everything
without tying you to
any interface
● custom directives
supported
10
★ session
★ user
★ documentation
★ timer
★ api version
directives
● work as prefixed
arguments or function
annotations
● can provide pretty
much everything
without tying you to
any interface
● custom directives
supported
11
@hug.directive()
def session(context_name='session', request=None, **kwargs):
"""Returns the session associated with the current request"""
return request and request.context.get(context_name, None) or None
#function annotation
@hug.get()
def my_endpoint(session: hug.directives.session):
session
#prefixed with hug_
@hug.get()
def my_endpoint(hug_session):
session
routing
● used for mapping
external interaction to
internal functions
● works as function
decorators
● can be used separately
from function/object
● supports chaining
12
★ urls
★ examples
★ response headers
★ status code
★ versions
★ response on invalid request
routing
● used for mapping
external interaction to
internal functions
● works as function
decorators
● can be used separately
from function/object
● supports chaining
13
# external.py
import hug
import internal
router = hug.route.API(__name__)
router.get('/home')(internal.root)
# internal.py
def root():
return 'Welcome home!'
routing
● used for mapping
external interaction to
internal functions
● works as function
decorators
● can be used separately
from function/object
● supports chaining
14
import hug
api = hug.get(on_invalid=hug.redirect.not_found)
@api.urls('/do-math', examples='number_1=1&number_2=2')
def math(number_1: hug.types.number, number_2: hug.types.number):
return number_1 + number_2
@api
def happy_birthday(name, age: hug.types.number):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
but wait! There’s more:
15
● different output formats (image, video, file streams)
● extensions through PyPI
● authentication
● command line interface
● easy testing
other python libraries I used
● shelve - data persistence
● warlock - model with validation
● jsonschema - model description used by warlock
16
“Hug is the best thing since sliced bread”
- Abraham Lincoln
17
Thanks!
Contact me:
arturstaniec@gmail.com
+ArturStaniec
@xklakoux
links:
http://www.hug.rest
18

More Related Content

PDF
Echtzeitapplikationen mit Elixir und GraphQL
PDF
Dataflow: Declarative concurrency in Ruby
PDF
Development of Ansible modules
PPTX
Inline and lambda function
PDF
Ansible Callback Plugins
PDF
Wrapping java in awesomeness aka condensator
PDF
Fabric for fun_and_profit
PDF
Introduction to Elixir
Echtzeitapplikationen mit Elixir und GraphQL
Dataflow: Declarative concurrency in Ruby
Development of Ansible modules
Inline and lambda function
Ansible Callback Plugins
Wrapping java in awesomeness aka condensator
Fabric for fun_and_profit
Introduction to Elixir

What's hot (18)

PDF
Templating in ansible
PDF
Angular Pipes Workshop
PDF
Kotlin 1.2: Sharing code between platforms
PPTX
Lua Study Share
PDF
Ansible 202
PDF
Three Objectionable Things
PPTX
10 tips for making Bash a sane programming language
PDF
Bootstrap |> Elixir - Easy fun for busy developers
PDF
Introduction to Erlang/(Elixir) at a Webilea Hands-On Session
PDF
Concurrency in Elixir with OTP
PDF
Flask With Server-Sent Event
PDF
Elixir and OTP
PDF
A deep dive into PEP-3156 and the new asyncio module
KEY
Perl: Hate it for the Right Reasons
PDF
ECMAScript 6
PDF
Replacing "exec" with a type and provider: Return manifests to a declarative ...
ODP
Modern Perl
Templating in ansible
Angular Pipes Workshop
Kotlin 1.2: Sharing code between platforms
Lua Study Share
Ansible 202
Three Objectionable Things
10 tips for making Bash a sane programming language
Bootstrap |> Elixir - Easy fun for busy developers
Introduction to Erlang/(Elixir) at a Webilea Hands-On Session
Concurrency in Elixir with OTP
Flask With Server-Sent Event
Elixir and OTP
A deep dive into PEP-3156 and the new asyncio module
Perl: Hate it for the Right Reasons
ECMAScript 6
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Modern Perl
Ad

Similar to Hug presentation for android tech talks #14 (20)

PDF
Python tools for testing web services over HTTP
PDF
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
PDF
Django at Scale
PDF
Let's read code: python-requests library
PDF
Muduo network library
PDF
Python Load Testing - Pygotham 2012
PDF
Python于Web 2.0网站的应用 - QCon Beijing 2010
PDF
Princeton RSE Peer network first meeting
PDF
Python lecture 11
PDF
Pycon - Python for ethical hackers
PDF
Python RESTful webservices with Python: Flask and Django solutions
PDF
Python client api
PDF
обзор Python
PDF
Web Development with Python and Django
PDF
PyCon2022 - Building Python Extensions
PDF
Balázs Bucsay - XFLTReaT: Building a Tunnel
PDF
SciPy 2022 Scikit-HEP
PDF
오픈소스 라이브러리 개발기
PPTX
Network programming using python
PDF
XFLTReaT: a new dimension in tunnelling (BruCON 0x09 2017)
Python tools for testing web services over HTTP
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Django at Scale
Let's read code: python-requests library
Muduo network library
Python Load Testing - Pygotham 2012
Python于Web 2.0网站的应用 - QCon Beijing 2010
Princeton RSE Peer network first meeting
Python lecture 11
Pycon - Python for ethical hackers
Python RESTful webservices with Python: Flask and Django solutions
Python client api
обзор Python
Web Development with Python and Django
PyCon2022 - Building Python Extensions
Balázs Bucsay - XFLTReaT: Building a Tunnel
SciPy 2022 Scikit-HEP
오픈소스 라이브러리 개발기
Network programming using python
XFLTReaT: a new dimension in tunnelling (BruCON 0x09 2017)
Ad

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Spectroscopy.pptx food analysis technology
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
PDF
Electronic commerce courselecture one. Pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
DOCX
The AUB Centre for AI in Media Proposal.docx
Machine learning based COVID-19 study performance prediction
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
MYSQL Presentation for SQL database connectivity
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation_ Review paper, used for researhc scholars
Spectroscopy.pptx food analysis technology
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
Electronic commerce courselecture one. Pdf
Advanced methodologies resolving dimensionality complications for autism neur...
20250228 LYD VKU AI Blended-Learning.pptx
Chapter 3 Spatial Domain Image Processing.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Empathic Computing: Creating Shared Understanding
Review of recent advances in non-invasive hemoglobin estimation
Digital-Transformation-Roadmap-for-Companies.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
MIND Revenue Release Quarter 2 2025 Press Release
The AUB Centre for AI in Media Proposal.docx

Hug presentation for android tech talks #14

  • 1. the easiest API for your apps with hug 1
  • 2. Mocking services ● static (no logic allowed) ● limited ● essential functions are for paid users only ● no full control over API 2
  • 3. hug ● written by Timothy Crosley ● currently on version 2.1.2 ● runs on python3 ● built on top of Falcon ● magic done once ● feature-filled ● as easy as writing definition 3 source: http://www.hug.rest
  • 4. bare minimum 4 # server.py import hug @hug.get() def hello(): return 'Hi there!' $ hug -f server.py run it with
  • 6. code included in the demo 6 '''Funny cat names in hug''' import hug cats = [] #starts up on server launch @hug.startup() def init(api): cats.extend(['fluffy','bubba','cuddles','meowly']) #default arguments make them not required @hug.get() def hello(name :hug.types.text='stranger'): '''Greets you on /v1/hello''' return 'Hi there ' + name + '!' #supports all http methods @hug.post('/cats') def add_cat(name :hug.types.text): '''Add cat name to the list''' cats.append(name) return {'result':'ok'} #easy versioning @hug.post('/cats', versions=2) def add_cat(name :hug.types.text): '''Add cat name to the list''' cats.append(name) return {'id':len(cats)-1} #supports URI params @hug.get('/cats/{id}') def get_cat(id :hug.types.number): '''Get cat name with specified id''' return cats[id] #provide examples for easy launch from documentation @hug.get('/cats', examples='length=3') def get_cats(length :hug.types.number=None): '''Get funny cat names''' if length: return cats[:length] else: return cats
  • 8. types ● used for validation or simple mutation of parameters ● work through function annotations ● various different types available and custom types are supported 8 ★ primitive types(text, number, boolean etc.) ★ delimited list ★ multiple types at once ★ more than, less than, length ★ cut off
  • 9. types ● used for validation or simple mutation of parameters ● work through function annotations ● various different types available and custom types are supported 9 @hug.type(extend=hug.types.text) def htmlcolor(value): '''HTML color code''' pattern = re.compile('#[0-9a-fA-F]{6}') m = pattern.match(value) if m: return m.group() else: raise ValueError('Value is not a html color code') @hug.post('/lamp/{id}/changecolor') def change_color(id :hug.types.number, color :htmlcolor()): return {'id':id,'color':color} @hug.type(extend=htmlcolor) def torgbtuple(value): '''Color tuple''' value = value.lstrip('#') return tuple(int(value[i:i + 2],16) for i in range(0, 6, 2)) @hug.post('/color') def get_rgb_touple(color :torgbtuple()): return {'red':color[0],'green':color[1],'blue':color[2]}
  • 10. directives ● work as prefixed arguments or function annotations ● can provide pretty much everything without tying you to any interface ● custom directives supported 10 ★ session ★ user ★ documentation ★ timer ★ api version
  • 11. directives ● work as prefixed arguments or function annotations ● can provide pretty much everything without tying you to any interface ● custom directives supported 11 @hug.directive() def session(context_name='session', request=None, **kwargs): """Returns the session associated with the current request""" return request and request.context.get(context_name, None) or None #function annotation @hug.get() def my_endpoint(session: hug.directives.session): session #prefixed with hug_ @hug.get() def my_endpoint(hug_session): session
  • 12. routing ● used for mapping external interaction to internal functions ● works as function decorators ● can be used separately from function/object ● supports chaining 12 ★ urls ★ examples ★ response headers ★ status code ★ versions ★ response on invalid request
  • 13. routing ● used for mapping external interaction to internal functions ● works as function decorators ● can be used separately from function/object ● supports chaining 13 # external.py import hug import internal router = hug.route.API(__name__) router.get('/home')(internal.root) # internal.py def root(): return 'Welcome home!'
  • 14. routing ● used for mapping external interaction to internal functions ● works as function decorators ● can be used separately from function/object ● supports chaining 14 import hug api = hug.get(on_invalid=hug.redirect.not_found) @api.urls('/do-math', examples='number_1=1&number_2=2') def math(number_1: hug.types.number, number_2: hug.types.number): return number_1 + number_2 @api def happy_birthday(name, age: hug.types.number): """Says happy birthday to a user""" return "Happy {age} Birthday {name}!".format(**locals())
  • 15. but wait! There’s more: 15 ● different output formats (image, video, file streams) ● extensions through PyPI ● authentication ● command line interface ● easy testing
  • 16. other python libraries I used ● shelve - data persistence ● warlock - model with validation ● jsonschema - model description used by warlock 16
  • 17. “Hug is the best thing since sliced bread” - Abraham Lincoln 17