Browse Courses

Rest Api

This document explains how to use the Python Requests library for HTTP communication, covering GET and POST requests, query strings, request/response objects, and practical examples for web APIs.

This document covers the use of the Python Requests library for HTTP communication, including GET and POST requests, query strings, request and response objects, and practical examples for interacting with web APIs.


Introduction to the Requests Library

The Requests library in Python simplifies sending HTTP/1.1 requests. It supports GET and POST methods, allowing easy interaction with web servers and APIs.


Making GET Requests

Import the library and send a GET request:

1import requests
2r = requests.get('https://www.ibm.com')

The response object r contains information about the request, such as status code, headers, and encoding. The status code 200 indicates success. The response headers and body can be accessed as follows:

1print(r.status_code)
2print(r.headers)
3print(r.text[:100])  # First 100 characters of HTML body

Query Strings in GET Requests

Query strings send additional information to the server via the URL. They start with ? and include parameter-value pairs separated by &:

ParameterValue
nameJoseph
ID123

In Python, use a dictionary for parameters:

1payload = {'name': 'Joseph', 'ID': '123'}
2r = requests.get('https://httpbin.org/get', params=payload)
3print(r.url)

The response body contains the query string data in JSON format.


Making POST Requests

POST requests send data in the request body, not the URL. Use the post() function and pass the payload to the data parameter:

1payload = {'name': 'Joseph', 'ID': '123'}
2r = requests.post('https://httpbin.org/post', data=payload)
3print(r.text)

Compare GET and POST requests:

  • GET: Data sent in URL, no request body
  • POST: Data sent in request body, not in URL

Conclusion

The Python Requests library provides a simple interface for sending GET and POST requests, handling query strings, and processing HTTP responses. Understanding these concepts is essential for working with web APIs and automating data exchange.


FAQ