Giter Club home page Giter Club logo

api-buddy's Introduction

API Buddy

Build Status PyPI version

Demo

Right now, only OAuth2 authentication is supported. It's the most common, and current gold standard for security best practices. Also most APIs use it. That said, I have no beef with all the APIs out there using something else, so feel free to open a ticket if you want something else supported. ๐ŸŽŸ

You can also always manually set headers.

Installation

As long as you have python 3.7 or higher (I recommend using pyenv), just:

pip install api-buddy

Usage

First, specify the API you're exploring in your preferences

# ~/.api-buddy.yaml
api_url: https://some.api.com

Then it's as easy as:

api get some-endpoint
=> 200
{
  "look": "I haz data",
  "thx": "API Buddy"
}

HTTP Method defaults to get:

api this-endpoint  # same as first example

You can add query params in key=val format:

api get \
  my/favorite/endpoint \
  first_name=cosmo \
  last_name=kramer

You can also add request body data in JSON format:

api post \
  some-endpoint \
  '{"id": 1, "field": "value"}'

๐Ÿค” Note the single-quotes. You can expand this accross multiple lines:

api post \
  some-endpoint \
  '{
     "id": 1,
     "field": "value"
  }'

Arguments

  • http_method: (optional, default=get) The HTTP method to use in your request.
    • It should be one of:
      • get
      • post
      • patch
      • put
      • delete
  • endpoint: (required) The relative path to an API endpoint.
    • AKA you don't need to type the base api url again here.
  • params: (optional) A list of key=val query params
  • data: (optional) A JSON string of requets body data.
    • You can't use this with get because HTTP.

Options

  • -h, --help: Show the help message
  • -v, --version: Show the installed version

Development

Requires:

Steps to start working:

  • Build and create the local venv with bin/setup
  • Make sure everything works with bin/test
  • Try the local cli with poetry run api --help
  • Find other management commands with bin/list

api-buddy's People

Contributors

fonsecapeter avatar pfonseca23 avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Forkers

antonydevanchi

api-buddy's Issues

PyPi MVP

Re-create your hacky bash scripts in clean, tested python. Add new features/nicer ui where possible

Handle response content-types better

Check response content-type header (instead of just naiively trying to turn it into JSON) and handle appropriately -- if it's a known binary type, just say it's a binary file for now and don't do anything but print something saying it's a binary.

Maybe later can add a --write or --save option to save the response content no matter what it is with a given name, which would be useful for big json responses too.

Colorize

Add colors + json formatting. Make preferences if possible (may need to nest a level deeper into preferences)

Add http method arg

Most exploration is GET, so should default to that. Should be able to:

api-buddy post a_postable_endpoint
api-buddy POST a_postable_endpoint
api-buddy a_getable_endpoint

Add custom headers

Start with just a preferences entry for them, maybe post mvp add cli options

NotADirectoryError on reauthentication

Might be a Python 3.7.2 thing, but webbrowser.open is raising this error:

Traceback (most recent call last):
  File "/Users/pfonseca/.pyenv/versions/3.7.2/bin/api", line 10, in <module>
    sys.exit(run())
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/cli.py", line 26, in run
    resp = send_request(sesh, prefs, interpolated_opts, PREFS_FILE)
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/network/request.py", line 138, in send_request
    sesh = reauthenticate(sesh, prefs, prefs_file)
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/network/session.py", line 46, in reauthenticate
    new_sesh = reauthenticate_strategy(sesh, prefs, prefs_file)
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/network/auth/oauth2.py", line 97, in reauthenticate_oauth2
    authorize_params=oauth2_prefs['authorize_params'],
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/network/auth/oauth2.py", line 50, in _authenticate
    webbrowser.open(authorization_url)
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/webbrowser.py", line 75, in open
    register_standard_browsers()
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/webbrowser.py", line 530, in register_standard_browsers
    raw_result = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/subprocess.py", line 395, in check_output
    **kwargs).stdout
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/subprocess.py", line 1522, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
NotADirectoryError: [Errno 20] Not a directory: 'xdg-settings'

this jupyter notebook ticket has some info but turns out it's just a problem with webbrowser. In any event, this error should be able to fail here. Probably any error actually, this browser step is pure sugar.

Add lightweight webserver during DSA

Instead of manually copy/pasting from the url, should look into starting a super lightweight webserver that handles the redirect and grabs the token + displays instructions on screen. This will likely be a bit of work but would be really nice and polished to not have to see an error page in your browser and have to know to copy/paste the url.

Add nice param interface

Similar to httpie but aiming to be much simpler and support fewer things.

api-buddy my_favorite_endpoint \
  param=val \  # query params
  data:val     # json POST data

Use docopt

Instead of using click -- it's just better

Add optional api version preference

Optional api version preference (ex v1, 2, ...) since this is common:

f'{api_url}/{version}/{endpoint}'

Something in the yaml should be plenty, no need to add cli option for this

---
api_version: 1

Handle POSTs better

A couple minor tweaks

  • Should use json instead of data in the call to requests.post
  • Should print the post data as json instead of the more yamly format that headers are printed with
    • Just think this is a little more intuitive

This one isn't really specific to POST, but:

  • Print the auth header
    • For better transparency

Update pygments

With the 2.3 -> 2.4 Pygments update, the old-style ansi color names were deprecated. Shellectric is currently using them and should update to the new ones.

% api get account
Traceback (most recent call last):
  File "/Users/pfonseca/.pyenv/versions/3.7.2/bin/api", line 6, in <module>
    from api_buddy.cli import run
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/cli.py", line 4, in <module>
    from .config.preferences import load_prefs
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/config/preferences.py", line 9, in <module>
    from ..validation.preferences import (
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/validation/preferences.py", line 11, in <module>
    from ..utils.formatting import flat_str_dict, format_yaml_list
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/utils/formatting.py", line 10, in <module>
    from ..config.themes import SHELLECTRIC, Shellectric
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/api_buddy/config/themes.py", line 18, in <module>
    class Shellectric(Style):  # type: ignore
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/pygments/style.py", line 124, in __new__
    ndef[0] = colorformat(styledef)
  File "/Users/pfonseca/.pyenv/versions/3.7.2/lib/python3.7/site-packages/pygments/style.py", line 81, in colorformat
    assert False, "wrong color format %r" % text
AssertionError: wrong color format '#ansifuchsia'

Handle Errors Better

Right now have a mix of assertions manual exits. Should centralize this and would be better to raise errors than handle exiting centrally as part of the cli logic.

Look into browser opening

Seems to not be working... maybe the library just needs an update. Good thing it handles this error already

Add get interface

Simple interface where, if given an endpoint, send a get request.

 $ api-buddy my-favorite-endpoint
=> response

Step through auth

Add command to step through each authentication step and return intermediate responses, aka code and token responses for oauth2.

Add config command

To update config from the console instead of manually updating the yaml.

Add spinner

Something entertaining while waiting on the netowrk, maybe the same thing miso uses
[= ] [ = ] [ =]

Add client credentials grant flow

This comes up a lot. Will definitely want to cover other grant types and even other auth types, but I think this should be next in line

Add OAuth Client

Should be able to authenticate (with select_profile=True), use the standard python pop-open browser + listen for token (see if https is possible here, definitely want that)

Handle Keyboard interrupt during data sharing agreement

Keyboard interrupts are handled gracefully during requests but not during the pause when authentication through the oath flow, particularly when the user is leaving the terminal to open the data sharing agreement in their browser.

Would be better to just handle this equally throughout the runtime, can't remember why it's only implemented during requests ๐Ÿคทโ€โ™‚

Also would be nice to print something explicitly saying a Keyboard Interrupt was encountered for full clarity

Make OAuth2 more configurable

Pretty much everything that's an argument in the python call to requests-oauthlib should live in the preferences, including but not limited to:

  • authorize url
  • token url
  • extra authorize params

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.