Python MongoDB

Module 4: REST API in Pure Python – Complete Chapter | Python & MongoDB Course

Module 4: REST API in Pure Python – Complete Chapter

In this module, we build REST APIs in pure Python without using frameworks like Flask or Django.
You will learn how to handle HTTP requests, send JSON responses, and integrate with MongoDB for CRUD operations.
By the end, you’ll be able to create a fully functional API for user management.

✅ Introduction to HTTP & REST Principles

REST (Representational State Transfer) is an architectural style for building APIs. Key concepts:

  • Use standard HTTP methods: GET, POST, PUT, DELETE.
  • Resources are identified via URLs, e.g., /users, /users/{id}.
  • Responses are typically in JSON format.
  • Stateless: each request contains all necessary information.

✅ Python’s http.server & BaseHTTPRequestHandler

Python’s built-in modules allow us to create HTTP servers without external frameworks.

from http.server import HTTPServer, BaseHTTPRequestHandler
import json

class MyHandler(BaseHTTPRequestHandler):
    def _set_headers(self, status=200, content_type="application/json"):
        self.send_response(status)
        self.send_header('Content-type', content_type)
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        response = {"message": "Hello, GET request!"}
        self.wfile.write(json.dumps(response).encode('utf-8'))

server_address = ('', 8000)
httpd = HTTPServer(server_address, MyHandler)
print("Server running on port 8000...")
httpd.serve_forever()

Notes:

  • Each HTTP method has a corresponding function: do_GET, do_POST, etc.
  • Use wfile.write() to send response bytes.

✅ Parsing Requests (GET, POST, PUT, DELETE)

from urllib.parse import urlparse, parse_qs

def do_GET(self):
    parsed_path = urlparse(self.path)
    query = parse_qs(parsed_path.query)
    self._set_headers()
    response = {"path": parsed_path.path, "query": query}
    self.wfile.write(json.dumps(response).encode('utf-8'))

Similarly, do_POST can read request body:

content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
data = json.loads(post_data.decode('utf-8'))

✅ Connecting API Routes with MongoDB CRUD

from pymongo import MongoClient
from bson import ObjectId

client = MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
users_collection = db["users"]

Example: GET /users

def do_GET(self):
    if self.path == "/users":
        self._set_headers()
        users = list(users_collection.find({}, {"_id":0}))
        self.wfile.write(json.dumps(users).encode('utf-8'))

Example: POST /users

def do_POST(self):
    if self.path == "/users":
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        user_data = json.loads(post_data.decode('utf-8'))
        result = users_collection.insert_one(user_data)
        self._set_headers(201)
        self.wfile.write(json.dumps({"inserted_id": str(result.inserted_id)}).encode('utf-8'))

✅ Implementing PUT & DELETE Endpoints

# PUT /users/{id}
def do_PUT(self):
    if self.path.startswith("/users/"):
        user_id = self.path.split("/")[-1]
        content_length = int(self.headers['Content-Length'])
        put_data = self.rfile.read(content_length)
        update_data = json.loads(put_data.decode('utf-8'))
        users_collection.update_one({"_id": ObjectId(user_id)}, {"$set": update_data})
        self._set_headers()
        self.wfile.write(json.dumps({"message": "User updated"}).encode('utf-8'))

# DELETE /users/{id}
def do_DELETE(self):
    if self.path.startswith("/users/"):
        user_id = self.path.split("/")[-1]
        users_collection.delete_one({"_id": ObjectId(user_id)})
        self._set_headers()
        self.wfile.write(json.dumps({"message": "User deleted"}).encode('utf-8'))

✅ Testing APIs with Postman

  • Use Postman to send GET, POST, PUT, DELETE requests to http://localhost:8000/users.
  • Check JSON responses and HTTP status codes (200, 201, 404, etc.).
  • Test invalid inputs to ensure error handling works correctly.

✅ Exercises

  • Create a Python REST API with /users endpoints for CRUD operations.
  • Implement GET all users, GET single user by ID, POST new user, PUT update, DELETE user.
  • Connect API to MongoDB and verify all operations.
  • Test APIs with Postman and handle invalid requests gracefully.

Congratulations! You have completed Module 4: REST API in Pure Python.
You can now build fully functional REST APIs in pure Python, handle HTTP requests and responses, integrate with MongoDB, and test APIs using Postman.
Next, we will move to advanced topics like authentication, validation, and async requests in Module 5.

Leave a Reply

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