blueFast
blueFast

Reputation: 44461

Python library to access the Closure Compiler Service API

I am trying to integrate the closure compiler into my deploy process. I have come accross this online tool which allows me to generate some javascript from the required components. I see that the tool can be accessed via an API, so that is what I want to integrate into my deploy scripts.

I do not want to reinvent the wheel, and was wondering if there is an already available python wrapper for this API. The examples provided are very low-level, and I have not found an alternative.

Can somebody point me to higher-level python library to access the Goggle Closure Compiler Service API?

Upvotes: 1

Views: 384

Answers (1)

Erik Kaplun
Erik Kaplun

Reputation: 38247

The examples at developer.google.com actually use Python, so that's a good starting point. However, it seems that the API is so small that even the official doc just chooses to use the urllib and httplib Python built-in modules. Generalizing that logic into a helper function or two really seems like a trivial task.

...

params = urllib.urlencode([
    ('js_code', sys.argv[1]),
    ('compilation_level', 'WHITESPACE_ONLY'),
    ('output_format', 'text'),
    ('output_info', 'compiled_code'),
  ])

# Always use the following value for the Content-type header.
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPConnection('closure-compiler.appspot.com')
conn.request('POST', '/compile', params, headers)

...

See https://developers.google.com/closure/compiler/docs/api-tutorial1

P.S. You can also peek into https://github.com/danielfm/closure-compiler-cli—it's a command line tool but the source demonstrates how simple the API really is.

So turning the above into a Pythonic API:

import httplib
import sys
import urllib
from contextlib import closing


def call_closure_api(**kwargs):
    with closing(httplib.HTTPConnection('closure-compiler.appspot.com')) as conn:
        conn.request(
            'POST', '/compile',
            urllib.urlencode(kwargs.items()),
            headers={"Content-type": "application/x-www-form-urlencoded"}
        )
        return conn.getresponse().read()


call_closure_api(
    js_code=sys.argv[1],
    # feel free to introduce named constants for these
    compilation_level='WHITESPACE_ONLY',
    output_format='text',
    output_info='compiled_code'
)

Upvotes: 3

Related Questions