RafaelXavier


A REST client interface for Python

Posted in Tech by admin on the July 15th, 2008

The py-restlib: [http://code.google.com/p/py-restlib] is a GNU GPL library that implements a REST client interface for Python.

Here it goes its Getting Started section:

Introduction

Py-restlib is supposed to be a simple REST client interface for python. But, it also claims that writing a python client to communicate with RESTful applications on the Web should be an easy task.

Getting Started

Download

Check out the latest release using svn:
svn checkout http://py-restlib.googlecode.com/svn/trunk/ py-restlib
svn checkout http://py-restlib.googlecode.com/svn/trunk/ py-restlib

If you want support for translating JSON format into python structures, download json-py package, and unzip it to json-py subdir.

Examples

The REST client


from restlib import *

users = Resource("http://hostname/api/users")

# List all users (GET /api/users)
users.get()

# List user where id==1 (GET /api/users/1)
users.get(1)

# List user where id==1 && foo=='bar' (GET /api/users/1?foo=bar)
users.get(1, foo='bar', ...)

# Create a new user (POST /api/users)
users.create(foo='bar', ...)

etc...

# You are also able to use it that way:
api = BaseResource("http://hostname/api")
api.users.get()
api.users.create(foo='bar')
etc...

The REST server (in this case a Ruby on Rails application)


class Api::UsersController < ApplicationController
    protect_from_forgery :except => :create
    # GET /api/users
    def index
        @users = User.find(:all) # FIXME: if param[id] - under construction

        request.format=:json if request.format=:html
        respond_to do |format|
            format.xml {render :x ml => @users.to_xml}
            format.json {render :json => @users.to_json}
        end
    end

    # POST /api/users
    def create    # FIXME: under construction
        request.format=:json if request.format=:html
        respond_to do |format|
            format.xml {render :x ml => params.to_xml}
            format.json {render :json => params.to_json}
        end
    end
end

Python POST request

Posted in Tech by admin on the July 14th, 2008

If you’re trying to send a python POST request with httplib, but it’s not working like example tells. Try this minor fix:

Here is an example session that shows how to “POST” requests:

>>> import httplib, urllib
>>> params = urllib.urlencode({’spam’: 1, ‘eggs’: 2, ‘bacon’: 0})
>>> headers = {”Content-Type”: “application/x-www-form-urlencoded”,
… “Accept”: “text/plain”}
>>> conn = httplib.HTTPConnection(”musi-cal.mojam.com:80″)
>>> conn.request(”POST”, “/cgi-bin/query”, params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
200 OK
>>> data = response.read()
>>> conn.close()

Thanks to wireshark and the working command below, so example above could be compared.

curl -d foo=bar http://localhost