All jobs

Migrate From drf-yasg to drf-spectacular in Django REST Framework

Yes. An agent replaces drf-yasg views, decorators and custom inspectors with drf-spectacular, validates the OpenAPI 3 schema, and opens a pull request.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

drf-yasg generates Swagger 2.0 and drf-spectacular generates OpenAPI 3, so this is a change of output format as well as of library. Decorators map across almost one to one. The custom classes a project wrote to bend drf-yasg do not, and those are where the agent spends its time. In a project like aeasringnar/django-RESTfulAPI, which pins drf-yasg==1.21.3, the standard wiring is small: drf_yasg in INSTALLED_APPS, a get_schema_view(openapi.Info(...)) in drfAPI/urls.py serving JSON, Swagger UI and ReDoc when CURRENT_ENV is dev, and two @swagger_auto_schema decorators in apps/public/views.py.

The customisation is larger. SWAGGER_SETTINGS names three project classes. BaseOpenAPISchemaGenerator in extensions/MyCustomSwagger.py overrides get_schema to build the tag list from URL namespaces. MySwaggerAutoSchema in the same file re-implements get_operation so an endpoint with no summary uses its description. MyDjangoRestResponsePagination is a PaginatorInspector describing the paginated envelope. The settings also define a Bearer API key under SECURITY_DEFINITIONS, while the views authenticate with the project's own JwtAuthentication class.

The agent maps each one to its drf-spectacular counterpart and deletes what has no reason to exist any more. REST_FRAMEWORK gains DEFAULT_SCHEMA_CLASS, the openapi.Info values move into SPECTACULAR_SETTINGS, and the three routes become SpectacularAPIView, SpectacularSwaggerView and SpectacularRedocView under the same dev condition. The summary rule becomes a small AutoSchema subclass overriding get_summary, and the tag list a postprocessing hook. The pagination inspector is removed outright: drf-spectacular asks the paginator for get_paginated_response_schema, and extensions/Pagination.py already defines it. The agent points out that the two descriptions disagree, since the inspector lists msg and code and the paginator's own schema does not, and asks which the API really returns.

Two items cannot be translated word for word. The upload endpoint declares openapi.Parameter(name='file', in_=openapi.IN_FORM, type=openapi.TYPE_FILE), and OpenAPI 3 has no form parameters; the agent describes it as a multipart/form-data request body with a binary file property inside @extend_schema. And drf-spectacular cannot guess what a custom authentication class does, so it warns that it could not resolve the authenticator and leaves those operations with no security. The agent adds an OpenApiAuthenticationExtension for JwtAuthentication that reproduces the header scheme from the old settings. It then runs python manage.py spectacular --file schema.yml --validate --fail-on-warn until it exits cleanly. This project's settings expect Redis and MySQL, and urls.py writes to the cache on import, so the agent starts local services in the sandbox or uses a settings override for generation and says which.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Migrate this Django REST Framework project from drf-yasg to drf-spectacular. Start with an inventory: every import from drf_yasg, every swagger_auto_schema and swagger_serializer_method decorator, the get_schema_view call and its routes, every key in SWAGGER_SETTINGS and REDOC_SETTINGS, and every project class that subclasses a drf-yasg generator, auto schema or inspector, with one line on what each customisation does. Before changing anything, generate the current schema with drf-yasg and save it. Then install drf-spectacular, set DEFAULT_SCHEMA_CLASS, move title, version, description, contact and license into SPECTACULAR_SETTINGS, and replace the schema routes with SpectacularAPIView, SpectacularSwaggerView and SpectacularRedocView at the same paths and under the same conditions. Convert each decorator to extend_schema (manual_parameters to parameters with OpenApiParameter, request_body to request, operation_summary and operation_description to summary and description, auto_schema=None to exclude=True). Reimplement each custom class with the drf-spectacular mechanism that fits (an AutoSchema subclass, a postprocessing hook, the paginator's get_paginated_response_schema, an OpenApiAuthenticationExtension) and delete the ones that become unnecessary. Form and file parameters have no OpenAPI 3 parameter form: describe them as a multipart request body. Run manage.py spectacular with --validate and --fail-on-warn and resolve every warning or list the ones you could not, with the reason. Compare the old and new schemas: every path and method present before must be present after, and report differences in parameters, response shapes, tags and security. If the project needs a database or cache to import its URL configuration, start what is needed or use a settings override, and say which. Remove drf-yasg from the manifests. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

A pull request that removes drf-yasg from requirements.txt and from the code, with a description organised as a mapping table: each old decorator, setting and custom class on the left, and what replaced it, or why it was deleted, on the right. For django-RESTfulAPI that table has the three classes named in SWAGGER_SETTINGS, the upload parameter, the security definition, and the three documentation routes.

It includes the output of the spectacular command with --validate, and a comparison of the saved drf-yasg schema against the new one: paths and methods that match, and the differences. Some differences are expected and labelled as such, since Swagger 2.0 definitions become components, and form parameters become a request body. Others are questions, like the pagination envelope fields.

A reviewer opens Swagger UI on a development server, tries the authorise button and the upload endpoint, and checks the comparison for any path that vanished. Anyone who generates a client from the old swagger.json needs to know the document is OpenAPI 3 now; the description says so at the top.

Run it on every Django service that still depends on drf-yasg

A company with several Django services tends to copy its Swagger setup between them, custom classes included, so the same migration repeats with small variations. Start one run per repository from a script: POST /o/{org}/sessions with the body above and that repository in resources. Give each a request_id that is a UUID v5 of the repository name, so starting the batch again after a network error returns the runs already created. Runs beyond the key's max_concurrent are created queued and start as earlier ones finish.

Because the services share code, read the first pull request before starting the rest. If the shared pagination or authentication classes need a decision, make it once and add it to the prompt for the remaining repositories.

The use case this job follows, with its automation and trigger: Upgrade dependencies weekly.

Why run it on Rush?

A schema migration is easy to get approximately right. The documentation page loads, most endpoints look the same, and the missing security scheme or the lost upload field goes unnoticed until a client team regenerates their SDK. What prevents that is generating both schemas and comparing them path by path, with validation set to fail on warnings. The agent does both in its sandbox, and the commands with their output are kept in the session transcript, so the comparison in the pull request is something a reviewer can check.

It also needs a running project, which is the awkward part on a shared machine. Generating the schema imports the URL configuration, and here that touches a cache and a database. The sandbox is the agent's own computer, so it can start those services, or prove an override is enough, without anyone's local setup being involved.

Frequently asked questions

What replaces @swagger_auto_schema?

@extend_schema from drf_spectacular.utils. Most arguments have direct counterparts: request_body becomes request, manual_parameters becomes parameters, and operation_summary and operation_description become summary and description. Parameters are OpenApiParameter objects with a location such as OpenApiParameter.QUERY.

Will my generated API clients break?

They will need regenerating. drf-yasg emits Swagger 2.0 and drf-spectacular emits OpenAPI 3, so the document structure differs even when the API does not. Operation ids and component names can also change, which renames methods and types in generated code. The agent's schema comparison lists those.

How do I document a file upload now?

As a request body. OpenAPI 3 dropped formData parameters, so a file field is a property with type string and format binary in a multipart/form-data body. A serializer with a FileField on a view using MultiPartParser produces that without a manual schema.

Why does drf-spectacular warn about my authentication class?

It knows the authentication classes that ship with Django REST Framework and common packages, and has no way to infer a custom one. Subclass OpenApiAuthenticationExtension, set target_class to your class, and return the security scheme. Until then, operations using that class are documented as if they needed no credentials.

Can both libraries run side by side during the move?

Yes. They use different settings and can serve at different URLs, so you can keep the drf-yasg routes while you check the new ones. The agent removes drf-yasg in the same pull request by default; ask it to leave both if you want a transition period.

More jobs like this: Upgrade dependencies weekly

Keep reading