Skip to main content

Claude Prompt to Build a Flask API with Marshmallow Validation

Build a Flask REST API with Marshmallow for request validation, response serialization, nested objects, pagination, and clean error handling.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
Build a Flask REST API for Event (conference/meetup management) using Marshmallow for validation and serialization. The API serves React SPA and mobile app clients. Implement: 1) Marshmallow schemas: a CreateSchema (write) with strict validation — title (str, 3-200 chars), start_date (datetime), location (str), max_attendees (int, 1-10000) as required, description (str, default empty), category (str, default "general"), is_virtual (bool, default false), ticket_price (decimal, default 0) as optional with defaults. Add validators: Length, Range, OneOf, Regexp for email format, URL format for website, phone number regex, future-only dates, and a @validates_schema method for end_date must be after start_date, virtual events must have a meeting_url, paid events must have refund_policy. 2) A ReadSchema (response) with nested schemas for organizer (user), venue (location details), speakers (list), sponsors (list), dump_only fields for attendee_count, is_sold_out, days_until_event, and conditional field inclusion using context (e.g., show revenue_total, internal_notes, cost_breakdown only for admin users). 3) Route handlers with proper schema loading: use schema.load() for request validation (raises ValidationError with field-level error messages), schema.dump() for responses, and schema.dump(many=True) for collections. 4) Global error handler for marshmallow.ValidationError that returns JSON with status, message, and errors object mapping field names to error arrays with per-field errors and human-readable messages. 5) Pagination schema accepting page/per_page params with maximum limits, returning items, meta (page, per_page, total, total_pages), links (self, next, prev). 6) File upload handling with Marshmallow: validate file type (JPEG, PNG, PDF for event materials), size limit (10 MB), and return file URL in response. 7) API versioning strategy using URL prefix (/api/v1/, /api/v2/) with schema evolution — add fields without breaking v1 clients.

What this prompt does

This prompt builds a Flask REST API for [resource_name] using Marshmallow for validation and serialization, aimed at [client_type] clients. It separates concerns into a CreateSchema for writes — with [required_fields] required and [optional_fields] optional with defaults — and a ReadSchema for responses, plus validators (Length, Range, OneOf, Regexp) on [validated_fields] and a @validates_schema method for [cross_field_validation].

The ReadSchema nests [nested_objects], marks [computed_fields] as dump-only, and conditionally includes [admin_only_fields] based on context for admin users. Route handlers use schema.load() for validated input (raising ValidationError with field-level messages), schema.dump() for single objects, and schema.dump(many=True) for collections, while a global handler for marshmallow.ValidationError returns [error_format] with per-field messages. It also adds a pagination schema with maximum limits returning [pagination_response], file upload validation for [allowed_file_types] up to [max_file_size], and a versioning strategy via [versioning_approach] that evolves schemas without breaking v1 clients. Keeping validation in the schema layer means malformed input is rejected before it reaches your handlers.

When to use it

  • You're building a Flask API consumed by a React SPA or mobile app and want strict input validation
  • You want write and read schemas separated so responses stay predictable as fields grow
  • You need nested serialization of related objects in responses
  • You want consistent, field-level error responses on validation failures
  • You need pagination with enforced maximum page sizes
  • You're versioning an API and must add fields without breaking existing clients
  • You want validation to reject bad data before it ever reaches your route handlers

Example output

The AI returns Marshmallow schema classes (Create and Read), validator definitions for [validated_fields], route handlers calling load/dump, a global error handler producing [error_format], a pagination schema enforcing a max per_page, a file-upload handler validating type and size, and a versioning section showing how to add fields safely. Expect code grouped by the seven numbered concerns rather than one file, so you can adopt the schemas and error handling independently.

Pro tips

  • Keep [required_fields] and [optional_fields] disjoint and explicit so the CreateSchema validates exactly what you intend
  • Put genuinely cross-field rules (end after start, paid events need a refund policy) in [cross_field_validation] via @validates_schema, not individual field validators
  • Use schema context to gate [admin_only_fields] so non-admins never see sensitive computed values
  • Cap page size in the pagination schema; without a max, a client can request an enormous per_page
  • Validate both type and [max_file_size] on uploads — checking only the extension is easy to bypass
  • Mark [computed_fields] as dump-only so clients can't try to write values your server derives
  • Use a @validates_schema method for [cross_field_validation] since rules spanning two fields can't live on either field alone
  • When evolving the API under [versioning_approach], add fields as optional so v1 clients keep working

Frequently Asked Questions

Why separate a CreateSchema from a ReadSchema?
Writes and reads have different shapes: the CreateSchema enforces strict input validation on `[required_fields]`, while the ReadSchema handles nested objects, computed dump-only fields, and conditional inclusion. Separating them keeps responses predictable and stops clients from writing to fields that should be read-only.
How are validation errors returned to the client?
A global handler catches `marshmallow.ValidationError` and returns `[error_format]`, a JSON structure mapping each field name to its error messages. This gives front-end clients per-field, human-readable feedback instead of a single opaque error string.
Can it hide certain fields from non-admin users?
Yes. The ReadSchema uses Marshmallow context to conditionally include `[admin_only_fields]`, so values like revenue or internal notes appear only when an admin requests the resource. Regular clients receive the response without those fields.
Does it validate uploaded files?
It validates uploads against `[allowed_file_types]` and enforces a `[max_file_size]` limit before accepting the file and returning its URL. Checking file type and size matters because relying on the filename extension alone is easy for a client to spoof.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in Django & Flask Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support