Django Rest Framework Tutorial Series

Jul 23, 2024

Django Rest Framework Tutorial Series

Introduction

  • Host: Justin Mitchell
  • Goal: Build a REST API step-by-step
  • Importance: Enables web apps to communicate with other software securely (e.g., React.js, Vue.js, Django, FastAPI)
  • Tools to be used: Pure Django REST API, Django REST Framework, Python client, JavaScript client, integration with Algolia
  • All code available on GitHub

Tools Overview

  • Django REST Framework (DRF): Simplifies building REST APIs
  • Python requests: Used to test API functionality
  • Django CORS Headers: Necessary for web-based components
  • VS Code: Recommended code editor

Setup

  1. Python virtual environment setup
    • Commands: python3.10 -m venv venv, source venv/bin/activate (Mac/Linux), venv\Scripts\activate (Windows)
  2. Directory setup
    • Commands: mkdir -p ~/dev/drf, cd ~/dev/drf
  3. Install Django and dependencies
    • Required packages: requirements.txt includes Django, DRF, PyYAML, Python Requests, Django CORS Headers
  4. Creating and running a Django project
    • Commands: django-admin startproject cfehome ., python manage.py runserver 8000

Building a Basic Python API Client

  1. Endpoint setup for testing: http://httpbin.org/anything
  2. Making GET requests using Python Requests
  3. JSON handling
  4. Sending data in requests (JSON and form-encoded)

Initial API Setup with Django

  1. Creating Django app for API
    • Commands: python manage.py startapp api, add api to INSTALLED_APPS in settings.py
  2. First API view: Returns JSON response
    • Create api/urls.py and include in main urls.py
    • Use JsonResponse to return data in views
  3. Testing with Python client: Confirm proper JSON responses

Adding Models and Serializers

  1. Model Setup: Product model with fields (title, content, price)
  2. Serialization: Convert model instance to JSON using Django forms' model_to_dict and DRF's serializers
  3. DRF Serializer: Custom serializer with fields, @property methods for dynamic data

Improving API with Django REST Framework

  1. Install DRF: Add rest_framework to INSTALLED_APPS

  2. API Views: Use DRF's APIView and Response classes; handle methods (GET, POST)

  3. Generic Views: Shorten code using ListCreateAPIView, RetrieveUpdateDestroyAPIView

  4. Permissions and Authentication

    • Permission classes (IsAuthenticated, IsAdminUser)
    • Custom permissions
    • Incorporate session and token-based authentication

Integrating with Third-Party API Services: Algolia

  1. Install and configure Algolia
    • Set up Algolia account and configure API keys
    • Implement Algolia-specific settings in Django settings
  2. Indexing Models: Define fields to be indexed in Algolia
  3. Performing Searches: Use Algolia's API client to search indexed data

Handling Cross-Origin Resource Sharing (CORS)

  1. Install Django CORS Headers
    • Commands: pip install django-cors-headers, add to INSTALLED_APPS and middleware
  2. Configure Allowed Origins
    • Add specific domains to CORS_ALLOWED_ORIGINS or use regex in CORS_URLS_REGEX

Frontend Integration

  1. Building a JavaScript Client
    • Login form and handling using JavaScript
    • Fetch requests to Django API, handling CORS issues
  2. JWT Authentication: Manage tokens, refresh and verify them, handle authentication
  3. Implementing Search with Algolia’s InstantSearch.js
    • Search box and results handling using Algolia's API
    • Real-time search features, filtering, and displaying results

Conclusion

  • Encouragement to build and test clients in various scenarios
  • Review and learn from existing APIs to enhance skills
  • Stay updated and adopt best practices for authentication and security