Skip to main content

REST API calls made easier

Project description

RESTEasy

REST API calls made easier

PyPI version Build Status Join the chat at https://gitter.im/rapidstack/RESTEasy

Installation

pip install resteasy

Usage and examples

Import

from resteasy import RESTEasy, json

api = RESTEasy(base_url='https://api.example.com',
               auth=('user', '****'),
               verify=False, cert=None, timeout=None,
               encoder=json.dumps, decoder=json.loads, debug=False)

# optional timeout
api.timeout = 60

Example 1: GitHub Jobs

api =  RESTEasy(base_url='https://jobs.github.com')

positions = api.route('positions.json')

positions.get(description='python', full_time=1)
# or
positions.do('GET', {'description': 'python', 'full_time': 1})

# GET https://jobs.github.com/positions.json?description=python&full_time=1

Example 2: All methods: GET, POST, PUT, PATCH, DELETE

api = RESTEasy(base_url='https://jsonplaceholder.typicode.com')

posts = api.route('posts')

### GET (fetch resources)
posts.get()
posts.get(userId=1)
posts.route(1).get()

### POST (create a resource)
posts.post(title='foo', body='bar', userId=1)

### PUT & PATCH (update a resource)
posts.route(1).put(id=1, title='foo', body='bar', userId=1)
posts.route(1).patch(title='foo')

### DELETE (delete a resource)
posts.route(1).delete()

Example 3: Chuck Norris jokes

from __future__ import print_function

api = RESTEasy(base_url='https://api.chucknorris.io')


### Print a random joke
jokes = api.route('jokes')
random = jokes.route('random')
print(random.get())

# GET https://api.chucknorris.io/jokes/random


### Get all categories
categories = jokes.route('categories').get()
print(categories)

# GET https://api.chucknorris.io/jokes/categories


### Print a random joke from each category
for category in categories:
    random_joke = random.get(category=category)
    print(category, ':', random_joke['value'])

    # GET https://api.chucknorris.io/jokes/random?category=<category>

Example 4: Using custom decoder: Parsing MyAnimeList HTML content

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.found = False
        self.anime = None

    def handle_starttag(self, tag, attrs):
        '''Inherited method'''
        if tag == 'title' and not self.found:
            self.found = True

    def handle_data(self, data):
        '''Inherited method'''
        if self.found and self.anime is None:
            self.anime = data

    def parse(self, content):
        '''Parse content and return object'''
        self.feed(content)
        return self

    def __repr__(self):
        return 'Anime({})'.format(self.anime.strip() if self.found else '')

parser = MyHTMLParser()

api = RESTEasy(base_url='https://myanimelist.net', decoder=parser.parse)

### One way
api.route('anime/1').get()

### Another way
api.route('anime', 1).get()

### Yet another way
api.route('anime').route(1).get()

### This is the last way I swear
api.route('anime').route(1).do('GET')

# GET https://api.jikan.me/anime/1

Debugging

To enable debugging just pass or set debug=True

api.debug = True

Once debugging is set to 'True', Every HTTP call will return debug information instead of doing the actual request

>>> posts.debug = True
>>> posts.get(userId=1)
{'endpoint': 'https://jsonplaceholder.typicode.com/posts',
 'kwargs': {'userId': 1},
 'method': 'GET',
 'session': <requests.sessions.Session at 0x7f1e8c8bfeb8>}

Exceptions

  • As this package uses requests module to perform HTTP calls, most exceptions will be raised by requests module itself.

  • In case API server returns HTTP status code outside the range of 200-299, It will raise resteasy.HTTPError

  • In case the returned content by API server is not parsable, It will raise resteasy.InvalidResponseError

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

RESTEasy-1.0.2.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

RESTEasy-1.0.2-py3-none-any.whl (5.2 kB view details)

Uploaded Python 3

File details

Details for the file RESTEasy-1.0.2.tar.gz.

File metadata

  • Download URL: RESTEasy-1.0.2.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.18.4 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.27.0 CPython/3.5.3

File hashes

Hashes for RESTEasy-1.0.2.tar.gz
Algorithm Hash digest
SHA256 e46d4dacc07690e097e95e0a12014cd1d5e13a273797a665b212996e27ae400b
MD5 664869368df9bf54f76abfbd6d741404
BLAKE2b-256 f5bfd2dac0064f1630f0bc5a365acf5d782ccc7d351248f5de30f567aa1d3c39

See more details on using hashes here.

File details

Details for the file RESTEasy-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: RESTEasy-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 5.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.18.4 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.27.0 CPython/3.5.3

File hashes

Hashes for RESTEasy-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 dc5159a2119ae770c25641a26d2e0aa3e1e3a0e8bf3897d53fc5236abbc790ee
MD5 e9facc5a009e2781013f705eab4ba67d
BLAKE2b-256 897438595907be1efa78bbb45c6342b9c13feecb0007b8e8e668109397219ec6

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page