Python http Module

The http module in Python provides classes and functions for implementing web servers and clients. It includes low-level HTTP protocol handling, higher-level HTTP server and client functionalities, and various utilities for working with HTTP headers and status codes.

Table of Contents

  1. Introduction
  2. Key Classes and Functions
    • http.client
      • HTTPConnection
      • HTTPSConnection
      • HTTPResponse
      • HTTPMessage
    • http.server
      • BaseHTTPRequestHandler
      • HTTPServer
      • SimpleHTTPRequestHandler
    • http.cookies
      • SimpleCookie
      • Morsel
    • http.HTTPStatus
  3. Examples
    • Making an HTTP Request
    • Creating a Simple HTTP Server
    • Handling Cookies
    • Using HTTP Status Codes
  4. Real-World Use Case
  5. Conclusion
  6. References

Introduction

The http module provides a set of tools for working with HTTP. This includes classes for creating HTTP clients and servers, handling cookies, and working with HTTP status codes. It is a versatile module that can be used to build web applications, APIs, and more.

Key Classes and Functions

http.client

The http.client module defines classes for making HTTP requests.

HTTPConnection

Represents an HTTP connection.

import http.client

conn = http.client.HTTPConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
conn.close()

HTTPSConnection

Represents an HTTPS connection.

import http.client

conn = http.client.HTTPSConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
conn.close()

HTTPResponse

Represents the response from an HTTP request.

HTTPMessage

Represents the headers of an HTTP message.

http.server

The http.server module defines classes for creating HTTP servers.

BaseHTTPRequestHandler

Base class for handling HTTP requests.

HTTPServer

Class for creating an HTTP server.

from http.server import HTTPServer, BaseHTTPRequestHandler

class SimpleHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(b"Hello, World!")

server = HTTPServer(("localhost", 8000), SimpleHandler)
print("Server started on http://localhost:8000")
server.serve_forever()

SimpleHTTPRequestHandler

A simple HTTP request handler that serves files from the current directory and below.

http.cookies

The http.cookies module defines classes for handling HTTP cookies.

SimpleCookie

A class for parsing and creating HTTP cookie headers.

from http.cookies import SimpleCookie

cookie = SimpleCookie()
cookie["name"] = "value"
cookie["name"]["domain"] = "example.com"
cookie["name"]["path"] = "/"
print(cookie.output())

Morsel

Represents a single cookie value.

http.HTTPStatus

The HTTPStatus class provides constants for HTTP status codes.

from http import HTTPStatus

print(HTTPStatus.OK)
print(HTTPStatus.NOT_FOUND)

Examples

Making an HTTP Request

import http.client

conn = http.client.HTTPConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()
print("Status:", response.status)
print("Reason:", response.reason)
data = response.read()
print("Data:", data)
conn.close()

Output:

Status: 200
Reason: OK
Data: b'<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n    ...'

Creating a Simple HTTP Server

from http.server import HTTPServer, BaseHTTPRequestHandler

class SimpleHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(b"Hello, World!")

server = HTTPServer(("localhost", 8000), SimpleHandler)
print("Server started on http://localhost:8000")
server.serve_forever()

Output:

Server started on http://localhost:8000

Handling Cookies

from http.cookies import SimpleCookie

cookie = SimpleCookie()
cookie["name"] = "value"
cookie["name"]["domain"] = "example.com"
cookie["name"]["path"] = "/"
print(cookie.output())

Output:

Set-Cookie: name=value; Domain=example.com; Path=/

Using HTTP Status Codes

from http import HTTPStatus

print("Status Code:", HTTPStatus.OK)
print("Status Code:", HTTPStatus.NOT_FOUND)

Output:

Status Code: HTTPStatus.OK
Status Code: HTTPStatus.NOT_FOUND

Real-World Use Case

Creating a REST API with http.server

from http.server import HTTPServer, BaseHTTPRequestHandler
import json

class APIHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api/data":
            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            response = {"message": "Hello, World!"}
            self.wfile.write(json.dumps(response).encode())
        else:
            self.send_response(404)
            self.end_headers()

server = HTTPServer(("localhost", 8000), APIHandler)
print("API server started on http://localhost:8000")
server.serve_forever()

Output:

API server started on http://localhost:8000

Conclusion

The http module in Python provides essential tools for working with HTTP. Whether you need to create HTTP clients or servers, handle cookies, or work with HTTP status codes, this module offers the functionality needed for web development and HTTP communication.

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare