Send request to REST Server using Python

REST (REpresentational State Transfer) is a type of software architecture that enables a client and server to communicate with each other in order to exchange resources and data. It is a popular method of communication between applications, providing a flexible way to access and manipulate data.

Python is a powerful programming language that can be used to send requests to REST servers. With the right tools and knowledge, it is easy to send and receive data from a REST server using Python.

This article will provide some practical examples to help get started.

Python’s requests library is a popular third-party package for making HTTP requests in Python. It enables developers to make HTTP requests such as GET and POST, as well as other more complex requests such as PUT and DELETE.

It includes features like HTTP authentication, cookies, and session handling. It also supports features like SSL verification, timeouts, and proxies.

The requests library is built on top of Python’s built-in http.client module, which provides the underlying functionality for making HTTP requests

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

Above is a Python code that defines a class Client that can be used to make HTTP requests to a web API.

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 *


Scroll to Top

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