bb-plane-fork/apps/api/plane/utils/openapi/responses.py
Dheeraj Kumar Ketireddy 514686d9d5
[WEB-4045] feat: restructuring of the external APIs for better maintainability (#7477)
* Basic setup for drf-spectacular

* Updated to only handle /api/v1 endpoints

* feat: add asset and user endpoints with URL routing

- Introduced new asset-related endpoints for user assets and server assets, allowing for asset uploads and management.
- Added user endpoint to retrieve current user information.
- Updated URL routing to include new asset and user patterns.
- Enhanced issue handling with a new search endpoint for issues across multiple fields.
- Expanded member management with a new endpoint for workspace members.

* Group endpoints by tags

* Detailed schema definitions and examples for asset endpoints

* Removed unnecessary extension

* Specify avatar_url field separately

* chore: add project docs

* chore: correct all errors

* chore: added open spec in work items

* feat: enhance cycle API endpoints with detailed OpenAPI specifications

- Updated CycleAPIEndpoint and CycleIssueAPIEndpoint to include detailed OpenAPI schema definitions for GET, POST, PATCH, and DELETE operations.
- Specified allowed HTTP methods for each endpoint in the URL routing.
- Improved documentation for cycle creation, updating, and deletion, including request and response examples.

* chore: added open spec in labels

* chore: work item properties

* feat: enhance API endpoints with OpenAPI specifications and HTTP method definitions

- Added detailed OpenAPI schema definitions for various API endpoints including Intake, Module, and State.
- Specified allowed HTTP methods for each endpoint in the URL routing for better clarity and documentation.
- Improved request and response examples for better understanding of API usage.
- Introduced unarchive functionality for cycles and modules with appropriate endpoint definitions.

* chore: run formatter

* Removed unnecessary settings for authentication

* Refactors OpenAPI documentation structure

Improves the organization and maintainability of the OpenAPI documentation by modularizing the `openapi_spec_helpers.py` file.

The changes include:
- Migrates common parameters, responses, examples, and authentication extensions to separate modules.
- Introduces helper decorators for different endpoint types.
- Updates view imports to use the new module paths.
- Removes the legacy `openapi_spec_helpers.py` file.

This refactoring results in a more structured and easier-to-maintain OpenAPI documentation setup.

* Refactor OpenAPI endpoint specifications

- Removed unnecessary parameters from the OpenAPI documentation for various endpoints in the asset, cycle, and project views.
- Updated request structures to improve clarity and consistency across the API documentation.
- Enhanced response formatting for better readability and maintainability.

* Enhance API documentation with detailed endpoint descriptions

Updated various API endpoints across the application to include comprehensive docstrings that clarify their functionality. Each endpoint now features a summary and detailed description, improving the overall understanding of their purpose and usage. This change enhances the OpenAPI specifications for better developer experience and documentation clarity.

* Enhance API serializers and views with new request structures

- Added new serializers for handling cycle and module issue requests, including `CycleIssueRequestSerializer`, `TransferCycleIssueRequestSerializer`, `ModuleIssueRequestSerializer`, and intake issue creation/updating serializers.
- Updated existing serializers to improve clarity and maintainability, including the `UserAssetUploadSerializer` and `IssueAttachmentUploadSerializer`.
- Refactored API views to utilize the new serializers, enhancing the request handling for cycle and intake issue endpoints.
- Improved OpenAPI documentation by replacing inline request definitions with serializer references for better consistency and readability.

* Refactor OpenAPI documentation and endpoint specifications

- Replaced inline schema definitions with dedicated decorators for various endpoint types, enhancing clarity and maintainability.
- Updated API views to utilize new decorators for user, cycle, intake, module, and project endpoints, improving consistency in OpenAPI documentation.
- Removed unnecessary parameters and responses from endpoint specifications, streamlining the documentation for better readability.
- Enhanced the organization of OpenAPI documentation by modularizing endpoint-specific decorators and parameters.

* chore: correct formatting

* chore: correct formatting for all api folder files

* refactor: clean up serializer imports and test setup

- Removed unused `StateLiteSerializer` import from the serializer module.
- Updated test setup to include a noqa comment for the `django_db_setup` fixture, ensuring clarity in the code.
- Added missing commas in user data dictionary for consistency.

* feat: add project creation and update serializers with validation

- Introduced `ProjectCreateSerializer` and `ProjectUpdateSerializer` to handle project creation and updates, respectively.
- Implemented validation to ensure project leads and default assignees are members of the workspace.
- Updated API views to utilize the new serializers for creating and updating projects, enhancing request handling.
- Added OpenAPI documentation references for the new serializers in the project API endpoints.

* feat: update serializers to include additional read-only fields

* refactor: rename intake issue serializers and enhance structure

- Renamed `CreateIntakeIssueRequestSerializer` to `IntakeIssueCreateSerializer` and `UpdateIntakeIssueRequestSerializer` to `IntakeIssueUpdateSerializer` for clarity.
- Introduced `IssueSerializer` for nested issue data in intake requests, improving the organization of serializer logic.
- Updated API views to utilize the new serializer names, ensuring consistency across the codebase.

* refactor: rename issue serializer for intake and enhance API documentation

- Renamed `IssueSerializer` to `IssueForIntakeSerializer` for better clarity in the context of intake issues.
- Updated references in `IntakeIssueCreateSerializer` and `IntakeIssueUpdateSerializer` to use the new `IssueForIntakeSerializer`.
- Added OpenAPI documentation for the `get_workspace_work_item` endpoint, detailing parameters and responses for improved clarity.

* chore: modules and cycles serializers

* feat: add new serializers for label and issue link management

- Introduced `LabelCreateUpdateSerializer`, `IssueLinkCreateSerializer`, `IssueLinkUpdateSerializer`, and `IssueCommentCreateSerializer` to enhance the handling of label and issue link data.
- Updated existing API views to utilize the new serializers for creating and updating labels, issue links, and comments, improving request handling and validation.
- Added `IssueSearchSerializer` for searching issues, streamlining the search functionality in the API.

* Don't consider read only fields as required

* Add setting to separate request and response definitions

* Fixed avatar_url warning on openapi spec generation

* Made spectacular disabled by default

* Moved spectacular settings into separate file and added detailed descriptions to tags

* Specify methods for asset urls

* Better server names

* Enhance API documentation with summaries for various endpoints

- Added summary descriptions for user asset, cycle, intake, issue, member, module, project, state, and user API endpoints to improve clarity and usability of the API documentation.
- Updated the OpenAPI specifications to reflect these changes, ensuring better understanding for developers interacting with the API.

* Add contact information to OpenAPI settings

- Included contact details for Plane in the OpenAPI settings to enhance API documentation and provide developers with a direct point of contact for support.
- This addition aims to improve the overall usability and accessibility of the API documentation.

* Reordered tags and improved description relavancy

* Enhance OpenAPI documentation for cycle and issue endpoints

- Added response definitions for the `get_cycle_issues` and `delete_cycle_issue` methods in the CycleIssueAPIEndpoint to clarify expected outcomes.
- Included additional response codes for the IssueSearchEndpoint to handle various error scenarios, improving the overall API documentation and usability.

* Enhance serializer documentation across multiple files

- Updated docstrings for various serializers including UserAssetUploadSerializer, AssetUpdateSerializer, and others to provide clearer descriptions of their functionality and usage.
- Improved consistency in formatting and language across serializer classes to enhance readability and maintainability.
- Added detailed explanations for new serializers related to project, module, and cycle management, ensuring comprehensive documentation for developers.

* Refactor API endpoints for cycles, intake, modules, projects, and states

- Replaced existing API endpoint classes with more descriptive names such as CycleListCreateAPIEndpoint, CycleDetailAPIEndpoint, IntakeIssueListCreateAPIEndpoint, and others to enhance clarity.
- Updated URL patterns to reflect the new endpoint names, ensuring consistency across the API.
- Improved documentation and method summaries for better understanding of endpoint functionalities.
- Enhanced query handling in the new endpoint classes to streamline data retrieval and improve performance.

* Refactor issue and label API endpoints for clarity and functionality

- Renamed existing API endpoint classes to more descriptive names such as IssueListCreateAPIEndpoint, IssueDetailAPIEndpoint, LabelListCreateAPIEndpoint, and LabelDetailAPIEndpoint to enhance clarity.
- Updated URL patterns to reflect the new endpoint names, ensuring consistency across the API.
- Improved method summaries and documentation for better understanding of endpoint functionalities.
- Streamlined query handling in the new endpoint classes to enhance data retrieval and performance.

* Refactor asset API endpoint methods and introduce new status enums

- Updated the GenericAssetEndpoint to only allow POST requests for asset creation, removing the GET method.
- Modified the get method to require asset_id, ensuring that asset retrieval is always tied to a specific asset.
- Added new IntakeIssueStatus and ModuleStatus enums to improve clarity and management of asset and module states.
- Enhanced OpenAPI settings to include these new enums for better documentation and usability.

* enforce naming convention

* Added LICENSE to openapi spec

* Enhance OpenAPI documentation for various API endpoints

- Updated API endpoints in asset, cycle, intake, issue, module, project, and state views to include OpenApiRequest and OpenApiExample for better request documentation.
- Added example requests for creating and updating resources, improving clarity for API consumers.
- Ensured consistent use of OpenApi utilities across all relevant endpoints to enhance overall API documentation quality.

* Enhance OpenAPI documentation for various API endpoints

- Added detailed descriptions to multiple API endpoints across asset, cycle, intake, issue, module, project, state, and user views to improve clarity for API consumers.
- Ensured consistent documentation practices by including descriptions that outline the purpose and functionality of each endpoint.
- This update aims to enhance the overall usability and understanding of the API documentation.

* Update OpenAPI examples and enhance project queryset logic

- Changed example fields in OpenAPI documentation for issue comments from "content" to "comment_html" to reflect the correct structure.
- Introduced a new `get_queryset` method in the ProjectDetailAPIEndpoint to filter projects based on user membership and workspace, while also annotating additional project-related data such as total members, cycles, and modules.
- Updated permission checks to use the correct attribute name for project identifiers, ensuring accurate permission handling.

* Enhance OpenAPI documentation and add response examples

- Updated multiple API endpoints across asset, cycle, intake, issue, module, project, state, and user views to include new OpenApiResponse examples for better clarity on expected outcomes.
- Introduced new parameters for project and issue identifiers to improve request handling and documentation consistency.
- Enhanced existing responses with detailed examples to aid API consumers in understanding the expected data structure and error handling.
- This update aims to improve the overall usability and clarity of the API documentation.

* refactor: update terminology from 'issues' to 'work items' across multiple API endpoints for consistency and clarity

* use common timezones from pytz for choices

* Moved the openapi utils to the new folder structure

* Added exception logging in GenericAssetEndpoint to improve error handling

* Fixed code rabbit suggestions

* Refactored IssueDetailAPIEndpoint to streamline issue retrieval and response handling, removing redundant external ID checks and custom ordering logic.

---------

Co-authored-by: pablohashescobar <nikhilschacko@gmail.com>
Co-authored-by: NarayanBavisetti <narayan3119@gmail.com>
2025-07-25 00:17:05 +05:30

492 lines
14 KiB
Python

"""
Common OpenAPI responses for drf-spectacular.
This module provides reusable response definitions for common HTTP status codes
and scenarios that occur across multiple API endpoints.
"""
from drf_spectacular.utils import OpenApiResponse, OpenApiExample, inline_serializer
from rest_framework import serializers
from .examples import get_sample_for_schema
# Authentication & Authorization Responses
UNAUTHORIZED_RESPONSE = OpenApiResponse(
description="Authentication credentials were not provided or are invalid.",
examples=[
OpenApiExample(
name="Unauthorized",
value={
"error": "Authentication credentials were not provided",
"error_code": "AUTHENTICATION_REQUIRED",
},
)
],
)
FORBIDDEN_RESPONSE = OpenApiResponse(
description="Permission denied. User lacks required permissions.",
examples=[
OpenApiExample(
name="Forbidden",
value={
"error": "You do not have permission to perform this action",
"error_code": "PERMISSION_DENIED",
},
)
],
)
# Resource Responses
NOT_FOUND_RESPONSE = OpenApiResponse(
description="The requested resource was not found.",
examples=[
OpenApiExample(
name="Not Found",
value={"error": "Not found", "error_code": "RESOURCE_NOT_FOUND"},
)
],
)
VALIDATION_ERROR_RESPONSE = OpenApiResponse(
description="Validation error occurred with the provided data.",
examples=[
OpenApiExample(
name="Validation Error",
value={
"error": "Validation failed",
"details": {"field_name": ["This field is required."]},
},
)
],
)
# Generic Success Responses
DELETED_RESPONSE = OpenApiResponse(
description="Resource deleted successfully",
examples=[
OpenApiExample(
name="Deleted Successfully",
value={"message": "Resource deleted successfully"},
)
],
)
ARCHIVED_RESPONSE = OpenApiResponse(
description="Resource archived successfully",
examples=[
OpenApiExample(
name="Archived Successfully",
value={"message": "Resource archived successfully"},
)
],
)
UNARCHIVED_RESPONSE = OpenApiResponse(
description="Resource unarchived successfully",
examples=[
OpenApiExample(
name="Unarchived Successfully",
value={"message": "Resource unarchived successfully"},
)
],
)
# Specific Error Responses
INVALID_REQUEST_RESPONSE = OpenApiResponse(
description="Invalid request data provided",
examples=[
OpenApiExample(
name="Invalid Request",
value={
"error": "Invalid request data",
"details": "Specific validation errors",
},
)
],
)
CONFLICT_RESPONSE = OpenApiResponse(
description="Resource conflict - duplicate or constraint violation",
examples=[
OpenApiExample(
name="Resource Conflict",
value={
"error": "Resource with the same identifier already exists",
"id": "550e8400-e29b-41d4-a716-446655440000",
},
)
],
)
ADMIN_ONLY_RESPONSE = OpenApiResponse(
description="Only admin or creator can perform this action",
examples=[
OpenApiExample(
name="Admin Only",
value={"error": "Only admin or creator can perform this action"},
)
],
)
CANNOT_DELETE_RESPONSE = OpenApiResponse(
description="Resource cannot be deleted due to constraints",
examples=[
OpenApiExample(
name="Cannot Delete",
value={"error": "Resource cannot be deleted", "reason": "Has dependencies"},
)
],
)
CANNOT_ARCHIVE_RESPONSE = OpenApiResponse(
description="Resource cannot be archived in current state",
examples=[
OpenApiExample(
name="Cannot Archive",
value={
"error": "Resource cannot be archived",
"reason": "Not in valid state",
},
)
],
)
REQUIRED_FIELDS_RESPONSE = OpenApiResponse(
description="Required fields are missing",
examples=[
OpenApiExample(
name="Required Fields Missing",
value={"error": "Required fields are missing", "fields": ["name", "type"]},
)
],
)
# Project-specific Responses
PROJECT_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Project not found",
examples=[
OpenApiExample(
name="Project Not Found",
value={"error": "Project not found"},
)
],
)
WORKSPACE_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Workspace not found",
examples=[
OpenApiExample(
name="Workspace Not Found",
value={"error": "Workspace not found"},
)
],
)
PROJECT_NAME_TAKEN_RESPONSE = OpenApiResponse(
description="Project name already taken",
examples=[
OpenApiExample(
name="Project Name Taken",
value={"error": "Project name already taken"},
)
],
)
# Issue-specific Responses
ISSUE_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Issue not found",
examples=[
OpenApiExample(
name="Issue Not Found",
value={"error": "Issue not found"},
)
],
)
WORK_ITEM_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Work item not found",
examples=[
OpenApiExample(
name="Work Item Not Found",
value={"error": "Work item not found"},
)
],
)
EXTERNAL_ID_EXISTS_RESPONSE = OpenApiResponse(
description="Resource with same external ID already exists",
examples=[
OpenApiExample(
name="External ID Exists",
value={
"error": "Resource with the same external id and external source already exists",
"id": "550e8400-e29b-41d4-a716-446655440000",
},
)
],
)
# Label-specific Responses
LABEL_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Label not found",
examples=[
OpenApiExample(
name="Label Not Found",
value={"error": "Label not found"},
)
],
)
LABEL_NAME_EXISTS_RESPONSE = OpenApiResponse(
description="Label with the same name already exists",
examples=[
OpenApiExample(
name="Label Name Exists",
value={"error": "Label with the same name already exists in the project"},
)
],
)
# Module-specific Responses
MODULE_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Module not found",
examples=[
OpenApiExample(
name="Module Not Found",
value={"error": "Module not found"},
)
],
)
MODULE_ISSUE_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Module issue not found",
examples=[
OpenApiExample(
name="Module Issue Not Found",
value={"error": "Module issue not found"},
)
],
)
# Cycle-specific Responses
CYCLE_CANNOT_ARCHIVE_RESPONSE = OpenApiResponse(
description="Cycle cannot be archived",
examples=[
OpenApiExample(
name="Cycle Cannot Archive",
value={"error": "Only completed cycles can be archived"},
)
],
)
# State-specific Responses
STATE_NAME_EXISTS_RESPONSE = OpenApiResponse(
description="State with the same name already exists",
examples=[
OpenApiExample(
name="State Name Exists",
value={"error": "State with the same name already exists"},
)
],
)
STATE_CANNOT_DELETE_RESPONSE = OpenApiResponse(
description="State cannot be deleted",
examples=[
OpenApiExample(
name="State Cannot Delete",
value={
"error": "State cannot be deleted",
"reason": "Default state or has issues",
},
)
],
)
# Comment-specific Responses
COMMENT_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Comment not found",
examples=[
OpenApiExample(
name="Comment Not Found",
value={"error": "Comment not found"},
)
],
)
# Link-specific Responses
LINK_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Link not found",
examples=[
OpenApiExample(
name="Link Not Found",
value={"error": "Link not found"},
)
],
)
# Attachment-specific Responses
ATTACHMENT_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Attachment not found",
examples=[
OpenApiExample(
name="Attachment Not Found",
value={"error": "Attachment not found"},
)
],
)
# Search-specific Responses
BAD_SEARCH_REQUEST_RESPONSE = OpenApiResponse(
description="Bad request - invalid search parameters",
examples=[
OpenApiExample(
name="Bad Search Request",
value={"error": "Invalid search parameters"},
)
],
)
# Pagination Response Templates
def create_paginated_response(
item_schema,
schema_name,
description="Paginated results",
example_name="Paginated Response",
):
"""Create a paginated response with the specified item schema"""
return OpenApiResponse(
description=description,
response=inline_serializer(
name=schema_name,
fields={
"grouped_by": serializers.CharField(allow_null=True),
"sub_grouped_by": serializers.CharField(allow_null=True),
"total_count": serializers.IntegerField(),
"next_cursor": serializers.CharField(),
"prev_cursor": serializers.CharField(),
"next_page_results": serializers.BooleanField(),
"prev_page_results": serializers.BooleanField(),
"count": serializers.IntegerField(),
"total_pages": serializers.IntegerField(),
"total_results": serializers.IntegerField(),
"extra_stats": serializers.CharField(allow_null=True),
"results": serializers.ListField(child=item_schema()),
},
),
examples=[
OpenApiExample(
name=example_name,
value={
"grouped_by": "state",
"sub_grouped_by": "priority",
"total_count": 150,
"next_cursor": "20:1:0",
"prev_cursor": "20:0:0",
"next_page_results": True,
"prev_page_results": False,
"count": 20,
"total_pages": 8,
"total_results": 150,
"extra_stats": None,
"results": [get_sample_for_schema(schema_name)],
},
summary=example_name,
)
],
)
# Asset-specific Responses
PRESIGNED_URL_SUCCESS_RESPONSE = OpenApiResponse(
description="Presigned URL generated successfully"
)
GENERIC_ASSET_UPLOAD_SUCCESS_RESPONSE = OpenApiResponse(
description="Presigned URL generated successfully",
examples=[
OpenApiExample(
name="Generic Asset Upload Response",
value={
"upload_data": {
"url": "https://s3.amazonaws.com/bucket-name",
"fields": {
"key": "workspace-id/uuid-filename.pdf",
"AWSAccessKeyId": "AKIA...",
"policy": "eyJ...",
"signature": "abc123...",
},
},
"asset_id": "550e8400-e29b-41d4-a716-446655440000",
"asset_url": "https://cdn.example.com/workspace-id/uuid-filename.pdf",
},
)
],
)
GENERIC_ASSET_VALIDATION_ERROR_RESPONSE = OpenApiResponse(
description="Validation error",
examples=[
OpenApiExample(
name="Missing required fields",
value={"error": "Name and size are required fields.", "status": False},
),
OpenApiExample(
name="Invalid file type",
value={"error": "Invalid file type.", "status": False},
),
],
)
ASSET_CONFLICT_RESPONSE = OpenApiResponse(
description="Asset with same external ID already exists",
examples=[
OpenApiExample(
name="Duplicate external asset",
value={
"message": "Asset with same external id and source already exists",
"asset_id": "550e8400-e29b-41d4-a716-446655440000",
"asset_url": "https://cdn.example.com/existing-file.pdf",
},
)
],
)
ASSET_DOWNLOAD_SUCCESS_RESPONSE = OpenApiResponse(
description="Presigned download URL generated successfully",
examples=[
OpenApiExample(
name="Asset Download Response",
value={
"asset_id": "550e8400-e29b-41d4-a716-446655440000",
"asset_url": "https://s3.amazonaws.com/bucket/file.pdf?signed-url",
"asset_name": "document.pdf",
"asset_type": "application/pdf",
},
)
],
)
ASSET_DOWNLOAD_ERROR_RESPONSE = OpenApiResponse(
description="Bad request",
examples=[
OpenApiExample(
name="Asset not uploaded", value={"error": "Asset not yet uploaded"}
),
],
)
ASSET_UPDATED_RESPONSE = OpenApiResponse(description="Asset updated successfully")
ASSET_DELETED_RESPONSE = OpenApiResponse(description="Asset deleted successfully")
ASSET_NOT_FOUND_RESPONSE = OpenApiResponse(
description="Asset not found",
examples=[
OpenApiExample(name="Asset not found", value={"error": "Asset not found"})
],
)