Send request to REST Server using Python

Python’s requests library provides all necessary classes and methods to query internet resources, including REST server.

Client class

from requests import Request, Session, exceptions
import json

class Client:
    def __init__(self, base_url):
        self.base_url = base_url

    def query(self, uri, method, body):
        parameter = {}
        if body is not None:
            parameter.update(body)

        r = self._make_request(uri, method, parameter)
        rp = r.prepare()

        s = Session()
        resp = s.send(rp)
        return json.loads(resp.text)

    def _make_request(self, uri, method, body):

        headers = {
            'Accept': 'application/json'
        }

        r = Request(method.upper(), self.base_url + uri, headers=headers)

        if body:
            if r.method in ["POST", "PUT", "PATH"]:
                r.json = body
            else:
                r.params = body

        return r

Use the class

client = Client("http://api-domain.com/")
resp = client.query('login', 'POST', {'username': 'tester', 'password': 'tester'})

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close