Token导航 LogoToken导航

Agent Skill · 开发

api-response-patterns(API response 模式)

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

api-response-patterns 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 18,535。

总安装 329周安装 14GitHub Stars 21下载 115核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:api-response-patterns(API response 模式)
来源仓库:https://github.com/thapaliyabikendra/ai-artifacts
仓库路径:skills/api-response-patterns
安装命令:
npx skills add https://github.com/thapaliyabikendra/ai-artifacts --skill api-response-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/thapaliyabikendra/ai-artifacts --skill api-response-patterns

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于构建统一且可预测的 REST API 响应结构,提升客户端集成体验。适用于成功/错误包装、元数据添加(如分页、版本号)和跨端点一致性设计。提供标准响应格式模板,包含状态码、消息体和附加信息字段。支持多客户端类型适配(Web、移动端),确保接口行为稳定可靠。

强调错误处理标准化,便于调试和维护,同时增强 API 的可观测性。

来源仓库内路径:skills/api-response-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/thapaliyabikendra/ai-artifacts --skill api-res…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

api-response-patterns 怎么安装?

在终端执行 npx skills add https://github.com/thapaliyabikendra/ai-artifacts --skill api-response-patt…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

api-response-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

api-response-patterns 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

api-response-patterns 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

api-response-patterns 用的人多吗?

公开数据是累计安装 329 次,近一周安装 14 次,下载 115 次,GitHub 21 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

api-response-patterns 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
api-response-patterns

API response 模式 · 本页

32921需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

API Response Patterns

Master API response wrapper patterns for building consistent, predictable REST APIs that clients love.

When to Use This Skill

  • Designing uniform API response contracts
  • Implementing success/error response wrappers
  • Standardizing error response formats
  • Adding metadata to API responses (pagination, timing, version)
  • Building APIs consumed by multiple client types (web, mobile, third-party)

Why Response Wrappers?

BenefitDescription
ConsistencyAll endpoints return same structure
PredictabilityClients know what to expect
MetadataInclude timing, pagination, version info
Error HandlingUniform error format across all endpoints
DebuggingInclude correlation IDs for tracing

Response Wrapper Patterns

1. Basic ResponseModel

// Application.Contracts/Models/ResponseModel.cs
public class ResponseModel<T>
{
    public bool IsSuccess { get; set; }
    public T Data { get; set; }
    public string Message { get; set; }
    public List<string> Errors { get; set; } = new();

    protected ResponseModel() { }

    protected ResponseModel(bool isSuccess, T data, string message, List<string> errors)
    {
        IsSuccess = isSuccess;
        Data = data;
        Message = message;
        Errors = errors ?? new List<string>();
    }

    public static ResponseModel<T> Success(T data, string message = null)
        => new(true, data, message, null);

    public static ResponseModel<T> Failure(string message)
        => new(false, default, message, new List<string> { message });

    public static ResponseModel<T> Failure(List<string> errors)
        => new(false, default, errors.FirstOrDefault(), errors);
}

// Non-generic version for operations without return data
public class ResponseModel : ResponseModel<object>
{
    public static ResponseModel Success(string message = null)
        => new() { IsSuccess = true, Message = message };

    public new static ResponseModel Failure(string message)
        => new() { IsSuccess = false, Message = message, Errors = new List<string> { message } };
}

2. Extended ApiResponse with Metadata

// Application.Contracts/Models/ApiResponse.cs
public class ApiResponse<T>
{
    public bool Success { get; set; }
    public T Data { get; set; }
    public string Message { get; set; }
    public ApiResponseMeta Meta { get; set; }
    public List<ApiError> Errors { get; set; } = new();

    public static ApiResponse<T> Ok(T data, string message = null) => new()
    {
        Success = true,
        Data = data,
        Message = message,
        Meta = new ApiResponseMeta()
    };

    public static ApiResponse<T> Fail(string message, string code = null) => new()
    {
        Success = false,
        Message = message,
        Errors = new List<ApiError>
        {
            new ApiError { Code = code ?? "ERROR", Message = message }
        },
        Meta = new ApiResponseMeta()
    };

    public static ApiResponse<T> Fail(List<ApiError> errors) => new()
    {
        Success = false,
        Message = errors.FirstOrDefault()?.Message,
        Errors = errors,
        Meta = new ApiResponseMeta()
    };
}

public class ApiResponseMeta
{
    public string Version { get; set; } = "1.0";
    public DateTime Timestamp { get; set; } = DateTime.UtcNow;
    public string RequestId { get; set; } = Guid.NewGuid().ToString("N")[..8];
    public long? ProcessingTimeMs { get; set; }
}

public class ApiError
{
    public string Code { get; set; }
    public string Message { get; set; }
    public string Field { get; set; }
    public object Details { get; set; }
}

3. Paginated Response

// Application.Contracts/Models/PagedApiResponse.cs
public class PagedApiResponse<T> : ApiResponse<List<T>>
{
    public PaginationInfo Pagination { get; set; }

    public static PagedApiResponse<T> Ok(
        List<T> items,
        long totalCount,
        int pageNumber,
        int pageSize,
        string message = null) => new()
    {
        Success = true,
        Data = items,
        Message = message,
        Meta = new ApiResponseMeta(),
        Pagination = new PaginationInfo
        {
            TotalCount = totalCount,
            PageNumber = pageNumber,
            PageSize = pageSize,
            TotalPages = (int)Math.Ceiling((double)totalCount / pageSize),
            HasPreviousPage = pageNumber > 1,
            HasNextPage = pageNumber * pageSize < totalCount
        }
    };
}

public class PaginationInfo
{
    public long TotalCount { get; set; }
    public int PageNumber { get; set; }
    public int PageSize { get; set; }
    public int TotalPages { get; set; }
    public bool HasPreviousPage { get; set; }
    public bool HasNextPage { get; set; }
}

Usage in AppServices

1. Basic CRUD Operations

public class ProductAppService : ApplicationService, IProductAppService
{
    private readonly IRepository<Product, Guid> _productRepository;
    private readonly ILogger<ProductAppService> _logger;

    public async Task<ApiResponse<ProductDto>> GetAsync(Guid id)
    {
        var product = await _productRepository.FirstOrDefaultAsync(x => x.Id == id);

        if (product == null)
        {
            return ApiResponse<ProductDto>.Fail(
                "Product not found",
                "PRODUCT_NOT_FOUND");
        }

        var dto = ObjectMapper.Map<Product, ProductDto>(product);
        return ApiResponse<ProductDto>.Ok(dto);
    }

    public async Task<PagedApiResponse<ProductDto>> GetListAsync(
        PagedAndSortedResultRequestDto input,
        ProductFilter filter)
    {
        var queryable = await _productRepository.GetQueryableAsync();

        var query = queryable
            .WhereIf(!filter.Name.IsNullOrWhiteSpace(),
                x => x.Name.Contains(filter.Name))
            .WhereIf(filter.CategoryId.HasValue,
                x => x.CategoryId == filter.CategoryId);

        var totalCount = await AsyncExecuter.CountAsync(query);

        var products = await AsyncExecuter.ToListAsync(
            query
                .OrderBy(input.Sorting ?? "Name")
                .PageBy(input.SkipCount, input.MaxResultCount));

        var dtos = ObjectMapper.Map<List<Product>, List<ProductDto>>(products);

        return PagedApiResponse<ProductDto>.Ok(
            dtos,
            totalCount,
            pageNumber: (input.SkipCount / input.MaxResultCount) + 1,
            pageSize: input.MaxResultCount);
    }

    public async Task<ApiResponse<ProductDto>> CreateAsync(CreateProductDto input)
    {
        try
        {
            // Validate uniqueness
            var exists = await _productRepository.AnyAsync(
                x => x.ProductCode == input.ProductCode);

            if (exists)
            {
                return ApiResponse<ProductDto>.Fail(
                    $"Product code '{input.ProductCode}' already exists",
                    "DUPLICATE_PRODUCT_CODE");
            }

            var product = new Product(
                GuidGenerator.Create(),
                input.ProductCode,
                input.Name,
                input.Price);

            await _productRepository.InsertAsync(product);

            var dto = ObjectMapper.Map<Product, ProductDto>(product);
            return ApiResponse<ProductDto>.Ok(dto, "Product created successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create product");
            return ApiResponse<ProductDto>.Fail(ex.Message, "CREATE_FAILED");
        }
    }

    public async Task<ApiResponse<bool>> DeleteAsync(Guid id)
    {
        var product = await _productRepository.FirstOrDefaultAsync(x => x.Id == id);

        if (product == null)
        {
            return ApiResponse<bool>.Fail("Product not found", "NOT_FOUND");
        }

        await _productRepository.DeleteAsync(product);

        return ApiResponse<bool>.Ok(true, "Product deleted successfully");
    }
}

2. Bulk Operations

public async Task<ApiResponse<BulkOperationResult>> BulkDeleteAsync(List<Guid> ids)
{
    var products = await _productRepository.GetListAsync(x => ids.Contains(x.Id));

    if (!products.Any())
    {
        return ApiResponse<BulkOperationResult>.Fail(
            "No products found",
            "NOT_FOUND");
    }

    await _productRepository.DeleteManyAsync(products);

    var result = new BulkOperationResult
    {
        RequestedCount = ids.Count,
        ProcessedCount = products.Count,
        SkippedCount = ids.Count - products.Count
    };

    return ApiResponse<BulkOperationResult>.Ok(
        result,
        $"Deleted {products.Count} of {ids.Count} products");
}

public class BulkOperationResult
{
    public int RequestedCount { get; set; }
    public int ProcessedCount { get; set; }
    public int SkippedCount { get; set; }
    public List<string> SkippedIds { get; set; } = new();
}

Error Response Patterns

1. Validation Error Response

public class ValidationErrorResponse
{
    public bool Success => false;
    public string Message => "Validation failed";
    public string Code => "VALIDATION_ERROR";
    public List<FieldError> Errors { get; set; } = new();

    public static ValidationErrorResponse Create(List<FieldError> errors) => new()
    {
        Errors = errors
    };
}

public class FieldError
{
    public string Field { get; set; }
    public string Message { get; set; }
    public object AttemptedValue { get; set; }

    public FieldError() { }

    public FieldError(string field, string message, object attemptedValue = null)
    {
        Field = field;
        Message = message;
        AttemptedValue = attemptedValue;
    }
}

2. Exception Filter for Consistent Errors

public class ApiExceptionFilter : IExceptionFilter
{
    private readonly ILogger<ApiExceptionFilter> _logger;

    public ApiExceptionFilter(ILogger<ApiExceptionFilter> logger)
    {
        _logger = logger;
    }

    public void OnException(ExceptionContext context)
    {
        var response = context.Exception switch
        {
            EntityNotFoundException ex => CreateNotFoundResponse(ex),
            AbpValidationException ex => CreateValidationResponse(ex),
            BusinessException ex => CreateBusinessErrorResponse(ex),
            UnauthorizedAccessException => CreateUnauthorizedResponse(),
            _ => CreateInternalErrorResponse(context.Exception)
        };

        context.Result = new ObjectResult(response)
        {
            StatusCode = GetStatusCode(context.Exception)
        };

        context.ExceptionHandled = true;
    }

    private int GetStatusCode(Exception ex) => ex switch
    {
        EntityNotFoundException => 404,
        AbpValidationException => 400,
        BusinessException => 422,
        UnauthorizedAccessException => 401,
        _ => 500
    };

    private ApiResponse<object> CreateNotFoundResponse(EntityNotFoundException ex) =>
        ApiResponse<object>.Fail(ex.Message, "NOT_FOUND");

    private ApiResponse<object> CreateValidationResponse(AbpValidationException ex) =>
        ApiResponse<object>.Fail(
            ex.ValidationErrors.Select(e => new ApiError
            {
                Code = "VALIDATION_ERROR",
                Field = e.MemberNames.FirstOrDefault(),
                Message = e.ErrorMessage
            }).ToList());

    private ApiResponse<object> CreateBusinessErrorResponse(BusinessException ex) =>
        ApiResponse<object>.Fail(ex.Message, ex.Code ?? "BUSINESS_ERROR");

    private ApiResponse<object> CreateUnauthorizedResponse() =>
        ApiResponse<object>.Fail("Unauthorized access", "UNAUTHORIZED");

    private ApiResponse<object> CreateInternalErrorResponse(Exception ex)
    {
        _logger.LogError(ex, "Unhandled exception");
        return ApiResponse<object>.Fail("An internal error occurred", "INTERNAL_ERROR");
    }
}

Controller Patterns

1. Standard Controller

[ApiController]
[Route("api/products")]
public class ProductController : AbpController
{
    private readonly IProductAppService _productAppService;

    public ProductController(IProductAppService productAppService)
    {
        _productAppService = productAppService;
    }

    [HttpGet("{id}")]
    [ProducesResponseType(typeof(ApiResponse<ProductDto>), 200)]
    [ProducesResponseType(typeof(ApiResponse<object>), 404)]
    public async Task<IActionResult> GetAsync(Guid id)
    {
        var response = await _productAppService.GetAsync(id);

        if (!response.Success)
        {
            return NotFound(response);
        }

        return Ok(response);
    }

    [HttpGet]
    [ProducesResponseType(typeof(PagedApiResponse<ProductDto>), 200)]
    public async Task<IActionResult> GetListAsync(
        [FromQuery] PagedAndSortedResultRequestDto input,
        [FromQuery] ProductFilter filter)
    {
        var response = await _productAppService.GetListAsync(input, filter);
        return Ok(response);
    }

    [HttpPost]
    [ProducesResponseType(typeof(ApiResponse<ProductDto>), 201)]
    [ProducesResponseType(typeof(ApiResponse<object>), 400)]
    public async Task<IActionResult> CreateAsync([FromBody] CreateProductDto input)
    {
        var response = await _productAppService.CreateAsync(input);

        if (!response.Success)
        {
            return BadRequest(response);
        }

        return CreatedAtAction(
            nameof(GetAsync),
            new { id = response.Data.Id },
            response);
    }

    [HttpDelete("{id}")]
    [ProducesResponseType(typeof(ApiResponse<bool>), 200)]
    [ProducesResponseType(typeof(ApiResponse<object>), 404)]
    public async Task<IActionResult> DeleteAsync(Guid id)
    {
        var response = await _productAppService.DeleteAsync(id);

        if (!response.Success)
        {
            return NotFound(response);
        }

        return Ok(response);
    }
}

2. Response Helper Extension

public static class ControllerExtensions
{
    public static IActionResult ToActionResult<T>(
        this ControllerBase controller,
        ApiResponse<T> response)
    {
        if (response.Success)
        {
            return controller.Ok(response);
        }

        var errorCode = response.Errors.FirstOrDefault()?.Code ?? "ERROR";

        return errorCode switch
        {
            "NOT_FOUND" => controller.NotFound(response),
            "VALIDATION_ERROR" => controller.BadRequest(response),
            "UNAUTHORIZED" => controller.Unauthorized(response),
            "FORBIDDEN" => controller.StatusCode(403, response),
            _ => controller.BadRequest(response)
        };
    }
}

// Usage
[HttpGet("{id}")]
public async Task<IActionResult> GetAsync(Guid id)
{
    var response = await _productAppService.GetAsync(id);
    return this.ToActionResult(response);
}

OpenAPI Documentation

// Swagger configuration
services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });

    // Add response examples
    c.OperationFilter<ApiResponseOperationFilter>();
});

public class ApiResponseOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // Add common error responses
        operation.Responses.TryAdd("400", new OpenApiResponse
        {
            Description = "Bad Request - Validation Error"
        });

        operation.Responses.TryAdd("401", new OpenApiResponse
        {
            Description = "Unauthorized"
        });

        operation.Responses.TryAdd("404", new OpenApiResponse
        {
            Description = "Not Found"
        });

        operation.Responses.TryAdd("500", new OpenApiResponse
        {
            Description = "Internal Server Error"
        });
    }
}

Best Practices

  1. Use consistent response structure - All endpoints should return the same wrapper
  2. Include error codes - Machine-readable codes alongside human messages
  3. Add metadata - Timestamps, request IDs for debugging
  4. Paginate lists - Always include pagination info for collections
  5. Document with OpenAPI - Generate accurate API documentation
  6. Handle all exceptions - Use exception filters for consistency
  7. Use appropriate HTTP status codes - Map response status to HTTP codes
  8. Include timing information - Help clients understand performance
  9. Version your API - Include version in responses and routes
  10. Log correlation IDs - Make debugging distributed systems easier

References

平台分布

Codex

34.84%
按下载量换算40

Claude

29.31%
按下载量换算34

Cursor

18.91%
按下载量换算22

Gemini CLI

8.83%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills