ShortIQ

ShortIQ

AI

50 AI Prompts for Django REST Framework and Python API Development

A practical set of 50 prompts for building production APIs with Django REST Framework. Covers project setup, models, serializers, viewsets, authentication, permissions, filtering, testing with pytest, and Docker deployment.

June 11, 2026ShortIQ Editorial Team

Using These DRF Prompts Effectively

Django REST Framework is one of the most complete API frameworks available for Python. Its serializer system, viewsets, router registration, and permission classes handle most of what an API needs with well-established patterns. The prompts here assume Django 5, DRF 3.15, Python 3.12, and PostgreSQL as the database. They work with any capable AI assistant.

Paste your existing models.py and serializers.py into the conversation before running prompts that generate views or tests — the model generates far more accurate code when it can see your actual field names and types rather than guessing from the description. Always specify whether you are using class-based views or function-based views, and whether you prefer ViewSets with routers or standalone APIView classes.

Project Setup and Configuration (Prompts 1-8)

Prompt 1: Create a production-ready Django 5 project structure for a REST API. Show the folder layout with apps for users, core, and api, a config folder for settings split into base.py, development.py, and production.py, a pyproject.toml with dev and prod dependency groups, and a manage.py that reads the DJANGO_SETTINGS_MODULE from the environment with a sensible default.

Prompt 2: Write a Django settings configuration using django-environ. Load all sensitive settings from a .env file, define required variables with helpful error messages if they are missing, configure the database from DATABASE_URL, configure Redis from REDIS_URL, and set sensible production defaults for SECURE_SSL_REDIRECT, HSTS, and CSRF trusted origins. Prompt 3: Create a Django REST Framework default settings block for settings.py. Configure JWT as the default authentication class using djangorestframework-simplejwt, set a custom default permission to IsAuthenticated, configure pagination to 20 items per page with a page_size query parameter, set the default renderer to JSONRenderer in production, and add a throttle rate of 100 requests per minute for authenticated users.

  • Prompt 4: Write a custom Django User model that extends AbstractBaseUser. Include email as the username field instead of the Django default username, add first_name, last_name, is_active, is_staff, date_joined, and an avatar URLField. Create a CustomUserManager with create_user and create_superuser methods. Show the AUTH_USER_MODEL setting.
  • Prompt 5: Create a Django health check endpoint that returns the API version from a VERSION setting, database connectivity status from a test query, Redis connectivity status, and the current UTC timestamp. Return 200 when healthy and 503 when any dependency check fails.
  • Prompt 6: Write a Django management command called seed_data that creates an admin user with a known password, 10 test users with random emails using faker, 5 example organisations, and 100 sample records for the main model. Make it idempotent so running it twice does not create duplicates.
  • Prompt 7: Create a Django middleware that adds a unique request ID to every request, attaches it to the response as an X-Request-ID header, injects it into the logging context so all log lines for a request include the ID, and measures the request duration and logs it on completion.
  • Prompt 8: Write a Django error handler setup that overrides the default 400, 403, 404, and 500 views to return consistent JSON responses instead of HTML. Add a custom exception handler for DRF that maps Django exceptions to DRF responses and adds a request_id field to every error response.

Models, Serializers, and Views (Prompts 9-28)

Prompt 9: Write a Django model for a SaaS subscription system with three models: Organisation (name, slug, plan_type enum with free/pro/enterprise, max_users, created_at), Membership (organisation FK, user FK, role enum with admin/member, joined_at), and Subscription (organisation FK, stripe_subscription_id, status, current_period_end, cancel_at_period_end). Add database indexes on all foreign keys and frequently queried fields.

Prompt 10: Create a DRF ModelSerializer for the Organisation model. Include nested serialiser for the current user membership role, a computed field showing the current member count, read-only fields for created_at and slug, and a validate_name method that checks for uniqueness case-insensitively. Show the create method that auto-generates the slug from the name. Prompt 11: Write a DRF ModelViewSet for the Organisation resource. The list endpoint should return only organisations the requesting user is a member of. The create endpoint should auto-create a membership record making the creator an admin. Override destroy to require admin role and prevent deleting the last organisation for a user.

  • Prompt 12: Create a DRF nested serialiser for a Post model with Author details embedded. Show read and write behaviour: on read return the nested author object, on write accept an author_id integer. Use SerializerMethodField for computed properties like word_count and reading_time.
  • Prompt 13: Write a DRF APIView for bulk creating records. Accept a list of up to 100 objects, validate each with the serialiser, run all inserts in a single database transaction that rolls back if any record fails validation, and return the count of created records with any validation errors keyed by index.
  • Prompt 14: Create a DRF action using @action on a ViewSet that generates a CSV export of all records. Accept filter query params, stream the response using StreamingHttpResponse so large exports do not time out, set the Content-Disposition header for file download, and format numbers and dates for Excel compatibility.
  • Prompt 15: Write a DRF serialiser with context-dependent field inclusion. The list endpoint returns a minimal serialiser with id, name, and created_at. The detail endpoint returns the full serialiser with all fields including nested relations. Use a mixin that switches serialiser class based on the action.
  • Prompt 16: Create a DRF endpoint that handles file uploads using FileField. Accept a single file up to 10MB, validate the content type from the file magic bytes rather than just the extension, store the file to an S3-compatible backend using django-storages, and return the public URL in the response.
  • Prompt 17: Write a DRF ModelSerializer with optimistic locking. Add a version integer field to the model, validate that the submitted version matches the current database version before updating, increment the version on each update, and return a 409 Conflict response if the versions do not match.
  • Prompt 18: Create a DRF read-only ViewSet for an analytics endpoint. Use Django ORM annotations and aggregation to return daily active users, total events, and top pages for a date range. Accept start_date and end_date query parameters, validate them with serialiser fields, and cache the result for 5 minutes using Django cache framework.
  • Prompt 19: Write a DRF pagination class for cursor-based pagination on a high-volume endpoint. Use the created_at timestamp as the cursor, support both forward and backward navigation, encode the cursor as an opaque base64 string, and return next and previous cursor values in the response.

Authentication, Permissions, Filtering, and Testing (Prompts 29-50)

Prompt 29: Write a complete JWT authentication setup for a Django REST Framework API using djangorestframework-simplejwt. Configure access tokens with a 15-minute lifetime and refresh tokens with a 7-day lifetime. Add a custom token claim that includes the user role. Write a serialiser for the login endpoint that validates credentials and returns both tokens. Override the refresh endpoint to rotate the refresh token on each use.

Prompt 30: Create a custom DRF permission class called IsOrganisationAdmin that checks whether the requesting user has an admin membership role for the organisation referenced in the request. Support checking by organisation_id in the URL kwargs, in the request body, or in the object. Return a descriptive error message when access is denied. Prompt 31: Write a DRF custom permission class called IsOwnerOrReadOnly. For safe methods (GET, HEAD, OPTIONS) allow any authenticated user. For write methods check that request.user matches the obj.owner field. Show how to attach it to a ViewSet using permission_classes and how to combine it with IsAuthenticated.

  • Prompt 32: Create a DRF filtering setup using django-filter. Add a FilterSet for the Post model that filters by category, author, published date range, and full-text search on title and content. Register it on the ViewSet and show how the filter fields appear as query parameters in the browsable API.
  • Prompt 33: Write a DRF custom ordering backend that allows clients to sort results by multiple fields using a comma-separated ordering query parameter. Validate that only whitelisted fields can be used for ordering, map public field names to internal database field names, and handle descending order with a leading minus sign.
  • Prompt 34: Create a Django Celery setup for background task processing. Configure Celery with Redis as the broker, write a task that sends a welcome email after user registration, call the task asynchronously from the registration view, add retry logic with exponential backoff for email delivery failures, and show how to monitor task status.
  • Prompt 35: Write a pytest-django test for a DRF ViewSet. Use the APIClient, authenticate with a test user using force_authenticate, test that the list endpoint returns only records belonging to the authenticated user, test that create validates required fields and returns field-level errors, and test that another user cannot access or modify the first user records.
  • Prompt 36: Create a pytest factory-boy setup for a Django project. Write factories for User, Organisation, and Membership that generate realistic test data using faker. Show how to use SubFactory for related models, how to create a scenario with a user who is admin of one organisation and a member of another, and how to use the factories in pytest fixtures.
  • Prompt 37: Write a DRF API versioning setup that supports both URL versioning (v1/endpoint) and header versioning (Accept: application/json; version=1). Show how to register v1 and v2 serialisers for the same ViewSet, how to deprecate v1 with a Deprecation response header, and how to sunset a version with a 410 Gone response.
  • Prompt 38: Create a Django signals setup that triggers side effects when a subscription is created or updated: send a confirmation email, log the event to an audit table, update a user count cache in Redis, and notify a webhook URL. Use post_save signals with dispatch_uid to prevent duplicate handler registration.
  • Prompt 39: Write a DRF rate throttle class that implements per-organisation rate limiting rather than per-user. The limit should be based on the plan type from the organisation model: 60 requests per minute for free plans and 600 per minute for pro plans. Cache the request count in Redis with the organisation ID as the key.
  • Prompt 40: Create a Django management command for running database health checks and reporting the status of pending migrations, long-running queries, table sizes, and index usage statistics. Format the output as a readable report suitable for a weekly operations review.

FAQ

Should I use Django REST Framework or FastAPI for a new Python API?

Use DRF if you are building a full application with Django ORM models, admin panel, migrations, and the full Django ecosystem. Use FastAPI if you need maximum performance, prefer async-first design, or are building a microservice where the full Django stack would be overkill. DRF has more batteries included; FastAPI is faster and has better async support but requires assembling more pieces yourself.

Do these prompts work with Django Ninja?

The model, signal, and Celery prompts work directly since they are Django-level concerns. The serialiser, viewset, permission, and throttle prompts are DRF-specific and need adaptation for Django Ninja, which uses Pydantic schemas and function-based view decorators instead. If you are using Ninja, specify this in the prompt and ask for the equivalent Ninja pattern.

What is the best way to document a DRF API?

The most widely used option is drf-spectacular, which generates an OpenAPI 3 schema from your DRF code. It integrates with ViewSets and serialisers automatically and provides Swagger UI and ReDoc at configurable endpoints. Add @extend_schema decorators to ViewSet methods for custom descriptions, request examples, and response schemas. The generated schema can also be used for client code generation.

How should I handle file uploads in DRF for production?

Use django-storages with an S3-compatible backend for production file storage. Configure a separate DEFAULT_FILE_STORAGE setting that uses S3 in production and local filesystem in development. Validate file types using the python-magic library to check the file signature rather than relying on the client-provided MIME type. Set a maximum file size limit in both the serialiser and your web server configuration.

Related free tools

If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.

Continue Reading

Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.

Free newsletter

Get new guides in your inbox

We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.

No spam. Unsubscribe any time.

Was this article helpful?

Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.

We use this to improve tutorials, examples, and technical depth.