easyapi
A framework I built for myself. It gives you a REST API from your Django models in 5 lines — pagination, filters, search, ordering, cache, ownership scoping, OpenAPI docs, auth, rate limiting, edge security and multi-tenant DB routing. The same engine also serves an optional MCP server, so AI agents can use your app through intent-named tools. If you don't have Django, easyapi init reads a MySQL or Postgres schema and generates the whole project.
I run it in six of my own products. Sharing it because I'd like help making it better — issues, PRs, and "this broke for me" reports are all welcome.
Install
pip install easyapi-django # framework only
pip install 'easyapi-django[gen-mysql]' # + generator for MySQL
pip install 'easyapi-django[gen-postgres]' # + generator for Postgres
The PyPI distribution is easyapi-django. Imports use from easyapi import .... The CLI is easyapi.
What it looks like
REST resources are one class. MCP toolsets (optional) are another. They reuse the same engine primitives — auth (BaseResource._authenticate), rate limiting (easyapi.rate_limit), sensitive-field scrubbing (easyapi.sensitive), multi-tenant DB routing (aset_tenant, activated during auth via apply_session_to_request on both surfaces) and the global SecurityMiddleware. Both classes inherit a common CoreResource base — today a thin seam, not a policy layer.
REST — BaseResource exposes a Django model as a CRUD endpoint:
from easyapi import BaseResource
from myapp.models import Space
class SpaceResource(BaseResource):
model = Space
That class gives you:
- REST endpoints (
GET, POST, PATCH, DELETE) with pagination, filters, search, ordering.
- OpenAPI 3.0.3 spec at
/openapi.json and an interactive docs page at /docs.
- Async dispatch, session + API-key + Bearer auth, per-IP rate limit, scanner blocking, multi-tenant DB routing.
MCP — Tools collects intent-named methods into an MCP tool registry. Type hints become JSON Schema (Draft 2020-12); docstrings become tool descriptions for the agent:
from typing import Literal
from pydantic import BaseModel
from easyapi import Tools, tool
class OrderOut(BaseModel):
id: int
status: str
class Orders(Tools):
scope = "orders:read"
async def find(
self,
status: Literal["open", "closed"] | None = None,
limit: int = 50,
) -> list[OrderOut]:
"""List the caller's orders, optionally filtered by status."""
qs = Order.objects.filter(owner_id=self.user_id)
if status:
qs = qs.filter(status=status)
return [OrderOut.from_orm(o) async for o in qs[:limit]]
@tool(scope="orders:write", destructive=True, rate_limit="10/m")
async def cancel(self, order_id: int, reason: str) -> OrderOut:
"""Cancel an order and refund the original payment method."""
order = await Order.objects.aget(pk=order_id)
await order.cancel(reason)
return OrderOut.from_orm(order)
Tools surface as <namespace>_<method> — orders_find, orders_cancel. The framework follows the MCP client name regex ^[a-zA-Z0-9_-]{1,64}$ (dots aren't accepted by Claude.ai). The namespace defaults to the lower-cased class name, trimmed of a trailing tools (so OrdersTools → orders); override via namespace = '...' on the Toolset.
Wire the routes in urls.py. Without toolsets=, only REST is mounted:
from easyapi import get_routes
urlpatterns = get_routes(
endpoints={'orders': OrderResource},
toolsets=[Orders, Billing],
)
You get /orders… for REST, /mcp for JSON-RPC, /openapi.json, /docs, /mcp/tools (browseable) and /mcp/tools.json (machine-readable).
If you don't have Django yet:
easyapi init
The CLI prompts for host, db, credentials. About ten seconds later you have a working Django project — every table is a model with a REST resource. Sensitive columns (password, token, api_key) are auto-masked. Read-only by default. Pass --writable when you mean it. Write your MCP tools as Tools subclasses on top of the generated models.
Why it exists
Two years ago I got tired of writing the same Django REST API for the tenth time — DRF, Ninja, FastAPI, all powerful, all the same boilerplate. So I wrote a small framework for myself: one class, set some attributes, get the endpoints. I called it easyapi.
When MCP showed up and some of my projects needed an agent surface, I expected to write a second codebase. Instead the MCP server sat on the same engine — auth was already there, rate limit was already there, the field whitelists were already there. Only the wire format changed.
So I cleaned up easyapi and put it on GitHub. REST is the core; MCP is an optional extra on the same engine.
What you get
REST (BaseResource)
- Async CRUD on Django models with pagination, filters, search, ordering.
?all=1 lists every row. No page cut and no meta, as limit=0 does; page and limit beside it are ignored. all=0, all=false and an empty value leave paging on. A Rules resource stops all at the ceiling instead (below).
- Strict routes. An endpoint key is the plain name (
'task', 'task/file') and matches task and task/... only, never tasks or task_x. On it, a path whose tail isn't an id (/task/undefined) is a 404 (easyapi.item_not_found) on GET/PATCH/DELETE, not the full list. A regex key still works for what a name can't say ('^logout$', r'^admin/account/\d+/subscription(/.*)?$'). A loose regex key ('task(.*)$', '^invoice') is refused at startup with ImproperlyConfigured, naming the plain key to use.
- OpenAPI 3.0.3 spec + Scalar UI.
- Cache with namespace invalidation. Writes don't blow away unrelated rows.
- Bulk
PATCH/DELETE. Send {"ids": [3, 5], ...} to the resource URL with no id in the path. update_obj/delete_obj run once per id, so overrides (soft delete, ownership, update_fields) still apply. The response lists the ids that worked under updated/deleted, and the ids that didn't under failed ({id, status, detail}). Status is 200 when at least one id succeeds and 400 when all of them fail.
- Value suggestions for filter UIs:
?distinct=<field> returns up to 20 distinct values of a text field over the filtered list (distinct_term + distinct_operator narrow them). Only fields in both list_fields and filter_fields, or the ones listed in distinct_fields (which may name related paths such as client__nickname); protected and sensitive ones return 403. Custom fields (custom__<name>) follow the same allowlists: list custom__<name> for one, or custom for every custom field, in filter_fields, distinct_fields and AGGREGATE_FIELDS. They filter only through ?filter=<json> conditions; as a query-string shorthand (?custom__sector=Retail) they return 400, as does custom__<name> on a model without CustomFieldMixin.
- Custom fields read and write the same shape. Models with
CustomFieldMixin return custom: {name: value} in the detail and take the same object in POST/PATCH, merged: only the names sent change and null clears one. An unknown name or an invalid value is a 400. Filters, segments and metrics reference a field as custom__<name>.
- Custom field definitions do the validation. Each field carries
validation (required, unique, min/max, min_length/max_length/pattern) and conditions (when it shows, in the filter format: groups {rules, logical_operator}, operator names, citing custom.<name> or a model field; values coerced to the field type on write): a required field must have a value only while its conditions show it, and only where the record is edited (REST create/update; aprepare(..., check_required=False) for forms and imports, and aset, skip it). Options are settings.options = [{value, label, order, hidden}]; a hidden option stays on the objects that have it but can't be chosen anew. Multi select (MULTI_SELECT) takes a list, stores one row per option, filters with in/all/not_in and groups metrics once per option. An archived field keeps its values and takes no writes; it is left out unless asked for (?archived= on the definitions list, archived=True in custom_fields_schema, values and get). Groups (CustomFieldGroup, through a group FK on the concrete field model) order the record sections. easyapi.custom_resources has CustomFieldResource (name and type fixed, options matched by value, delete only archived, GET {id}/dependencies) and CustomFieldGroupResource (PATCH sort with {order: [ids]}, PATCH {id}/fields with {fields: [ids]}) to subclass with your models, and create_custom_field to create one by code with the same rules; custom_fields_schema lists all of it for segment and form UIs.
- Empty and null are told apart. Filters
isnull/isnotnull match NULL only; isempty/isnotempty also take '' on text fields; none of them takes a value (on a custom field, both mean no value). Writes store '' as NULL on text fields with null=True, blank=True.
- Dates are calendar days. Named periods (
today, this_month, last_7_days, ...) take no value; last_7_days is 7 days including today and next_7_days today and the 6 after it. A YYYY-MM-DD value is the whole calendar day. Days are cut in the user's timezone, or in the session account's with FILTER_TIMEZONE = 'account' (same day for every user and for background jobs), in filters, segments and /aggregate.
- One filter field over several columns. A value kept in more than one place (a category on the record, or on its split lines) filters as one field: declare
filter_aliases = {'category_id': ['category_id', 'lines__category_id']} on the Django model. A rule on the alias matches when any target does; a negative rule (not_*) or isnull/isempty matches when every target does ("no category is X"). It applies wherever conditions run: ?filter=, saved filters and /aggregate. The whitelists (filter_fields, AGGREGATE_FIELDS) check the alias name, not its targets.
/aggregate returns readable charts. limit counts the groups of the first non-date field (default and ceiling AGGREGATE_MAX_GROUPS, 50; above it a 400); the date and the other fields are never cut. Every grouped answer carries groups: {field, total, shown, other, limit, max_limit}, and "other": true gathers the rest as one __other__ group.
- Conditions through M2M and reverse relations don't repeat rows. Each one is a subquery of ids, so an
/aggregate sum filtered by tag counts each record once. In an AND group, the rules on one relation hold on the same related row ("event X after A and before B"); a field that repeats ("tag A and tag B", the values of all) takes a row per repetition, with the group's other rules on each. Rules in different groups hold on different rows.
- Tags by id or name. Set
tag_scope (fields of the tag model, e.g. {'context': 1}, or a property such as {'project_id': self.obj.project_id}) and the tags M2M takes ids or names in POST/PATCH: a name is created in the scope when missing, a tag outside it is a 400. The detail returns tags: [{id, name}].
- Ownership scoping. One attribute (
owner_field = 'owner_id') restricts every CRUD operation to rows owned by the authenticated user — the cheapest IDOR defense I know.
MCP (Tools + MCPServer)
- Intent-named tools: each public method is a tool;
_underscore methods stay private. A public method inherited from a base class (can_write, get_spaces on your project's Tools base) is a helper, not a tool, unless it carries @tool.
- JSON Schema (Draft 2020-12) generated from type hints; raw schema escape hatch when you need it (
@tool(input_schema={...})).
- Docstrings become tool descriptions for the agent — the full docstring is published, not just the first line.
- MCP
annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) via @tool(...). Read-scoped tools get readOnlyHint + idempotentHint automatically; override per-method when needed.
- Per-tool
scope and rate_limit ('10/m' shorthand or {'limit': N, 'window': seconds}). tools/list filters by the caller's OAuth scope so an agent only sees what it can call.
- Class-level
default_output_schema (set to False when methods return free-shape dict so the agent isn't misled by an auto-derived loose schema).
- Pinned envelope:
{tool, code, data} on success; {tool, code, message, ...} on error. Error codes are stable strings: OK, VALIDATION_ERROR, NOT_FOUND, FORBIDDEN, INSUFFICIENT_SCOPE, RATE_LIMITED, METHOD_NOT_ALLOWED, INTERNAL.
- Caller context filled in on every call, same names as on a REST resource:
self.user, self.account, self.user_id, self.account_id, self.tz (the user's timezone) and self.account_db (the account's database alias, already active). self.calc_timezone() gives the timezone for calendar cuts, as in REST (FILTER_TIMEZONE). An account that can't be resolved fails the call instead of running on the default database.
before_call / after_call hooks for audit and membership preloading.
- Server instructions:
EASYAPI['MCP_INSTRUCTIONS'] (a string) is sent as instructions in the initialize response, so the client learns when to use each tool before the first call. Unset, the field is omitted.
MCPTestClient drives the registry in-process — unit tests don't need HTTP.
Shared engine — reused by both surfaces (not held on the CoreResource base, which is an empty seam today):
- Bearer +
X-Api-Key + session-cookie auth on REST, through one authenticator (easyapi.rules.authenticator); /mcp takes only Bearer.
- Pre-auth per-IP throttling, scanner blocking and semantic invalid-request detection — via the global
SecurityMiddleware, so both surfaces are covered.
- Sliding session TTLs via Redis
GETEX. Configure with SESSION_TTL (default 1800s) and API_SESSION_TTL (default 300s).
- Sensitive-field scrubbing (
password, api_key, token baseline plus your additions) — applied on both REST and MCP responses (each surface scrubs with its own serializer over the shared is_sensitive).
- Multi-tenant DB routing.
apply_session_to_request is the single activation authority: Bearer, API-key and Redis-loaded sessions reach it inside _authenticate; a session already on the request was applied earlier by AuthMiddleware. Either way the connection is switched for the request on both surfaces.
- Async end-to-end. Async ORM, async Redis, async dispatch.
REST-only — enforced in BaseResource._dispatch:
- Authenticated abuse blocking by tenant/user or API-key digest.
Global read-only mode — EASYAPI = {'READ_ONLY': True} rejects every non-GET REST request with 405; for MCP it allows only tools classified as read-only (a read scope or @tool(read_only=True)) and rejects all other tools/call requests with METHOD_NOT_ALLOWED.
Full docs and reference: https://github.com/ssjunior/easyapi-django
Rules: one place for REST and MCP
A BaseResource and a toolset each carry their own copy of a model's rules, and copies drift. easyapi.rules puts them in one place: a Rules class per model declares what exists, who sees it, who may change it and what happens on a write. The REST Resource and the MCP Tools only translate requests into its operations, so both channels apply the same rule.