python
29 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
import re
class APIVersionMiddleware:
"""Extract API version from request and add to request object."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Try to extract from Accept header first
accept = request.META.get('HTTP_ACCEPT', '')
version_match = re.search(r'version=(\d+\.\d+)', accept)
if version_match:
request.api_version = version_match.group(1)
elif request.path.startswith('/api/v'):
# Extract from URL: /api/v2/...
parts = request.path.split('/')
if len(parts) > 2 and parts[2].startswith('v'):
request.api_version = parts[2][1:] # Remove 'v' prefix
else:
request.api_version = '1.0' # Default
else:
request.api_version = '1.0'
response = self.get_response(request)
response['API-Version'] = request.api_version
return response
1 file · python
Explain with highlit
API versioning via middleware provides clean URL routing. I extract version from Accept header or URL prefix and set it on the request object. Views can check request.api_version to return appropriate responses. For breaking changes, I maintain separate serializer classes per version. Middleware is cleaner than versioning libraries for simple cases. I default to latest version for backwards compatibility. This pattern centralizes version logic and keeps view code focused on business logic. For complex APIs, DRF's built-in versioning is more feature-complete.
Related snips
ruby
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
jwt
authentication
api
by Kai Nakamura
2 tabs
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
ruby
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
rails
caching
http-caching
by Alex Kumar
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
graphql
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
createdAt: String!
GraphQL API with Spring Boot
java
graphql
spring-boot
by David Kumar
3 tabs
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
Share this code
Here's the card — post it anywhere.