a 在API准备前前前端建房:没有粉碎定点 (中文 (Chinese Simplified))

a 在API准备前前前端建房:没有粉碎定点

Saturday, 13 December 2025

//

10 minute read

一. 导言 导言 导言 导言 导言 导言 一,导言 导言 导言 导言 导言 导言

在等待后端 API 准备就绪之前, 你被阻挡了多少次? 或者你花了多少小时来维持那些在需求改变时变得僵化的虚伪数据?

输入 mostlylucid.mockllmapi - ASP.NET核心模拟平台,该平台使用大语言模型来产生现实的、符合背景的在空中的API反应。你没有维护JSON装置,而是获得智能模型,以适应你的要求,并记住每通电话的状态。

它所支持的是: 您需要的每一项协议 — — REST、图形QL、GRPC、信号R、服务器启动事件和 OpenAPI 。 与静态固定装置不同,响应是根据您的请求动态生成的,这使得多步工作流程和复杂的测试情景变得微不足道。

项目链接

N Nuget 元数 N Nuget 元数 GitHub 释放 许可证:无许可证

使用它的三种方法

您可以以三种方式使用 mockllmapi mostlucid. mockllmapi, 取决于您希望您的 dev 环境有多孤立 :

  1. ASP.NET核心NGGet软件包 - 添加到您现有的项目中
  2. 独立 CLI 工具 - 跨平台可执行程序(从 释放释放)
  3. 嵌套容器 - 需要零安装

杀手特征:上下文内存

完整的指南 : APPI 参考文件

传统的模拟API有一个致命的缺陷: 每一个请求都是独立的。 给一个有42号身份证的用户, 然后去取他们的订单, 然后你就会收到99号身份证的订单。 没有一致性 。

AIPI 背景 在相关请求中共享内存来解决这个问题:

// Request 1: Get a user
// Note: 'context' is a simple query parameter - no cookies or sessions needed
fetch('/api/users/123?context=checkout-session')
// Response: { id: 42, name: "Alice Smith", email: "[email protected]" }

// Request 2: Get orders (same context parameter)
fetch('/api/orders?userId=42&context=checkout-session')
// Response: { userId: 42, customerName: "Alice Smith", items: [...] }
// Perfect! Same user, consistent data

专卖局长在同一背景下看待以前的请求,并得出一致的数据。 这是多步工作流程的游戏变换器 。

特点:

生命周期:

  • 无活动15分钟后自动到期(可配置)
  • 每次请求都会刷新计时器

行为 :

  • 从回复中智能提取所有字段

安全性 :

  • 零内存泄漏 - 环境清理

使用案例:

  • 完全适合 CI/ CD - 运行之间无状态

快速启动

备选方案1:NuGet 软件包

dotnet add package mostlylucid.mockllmapi
// Program.cs
builder.Services.AddLLMockApi(builder.Configuration);
app.MapLLMockApi("/api/mock");

备选办法2:CLI工具

# Download from https://github.com/scottgal/LLMApi/releases
llmock serve --port 5000

备选方案3: 备选办法 3: 嵌入器

完整的指南 : doccker 部署指南

git clone https://github.com/scottgal/LLMApi.git
cd LLMApi
docker compose up -d

先决条件:LLM 后端

你需要 一号Ollama、OpenAI或LM工作室:

# Recommended: Ollama with ministral-3:3b (ultra-fast, accurate JSON generation)
ollama pull ministral-3:3b

见见 《奥亚马示范指南》 供所有示范建议和比较之用。

立即尝试

一旦运行中, 请提出您的第一个请求 :

curl http://localhost:5000/api/mock/users
# Response: [{"id": 1, "name": "Alice Johnson", "email": "[email protected]"}, ...]

就是这样,你现在有一个工作模拟API 产生现实的需求数据。

真实示例: 从 mostlucid.net 搜索

这是这个博客上的实际搜索代码 这是未变的生产前端代码无需对模拟作任何调整:

// typeahead.js from mostlylucid.net
export function typeahead() {
    return {
        query: '',
        results: [],
        search() {
            fetch(`/api/search/${encodeURIComponent(this.query)}`)
                .then(response => response.json())
                .then(data => { this.results = data; });
        }
    }
}

嘲笑它:

# Using CLI
llmock serve --port 5000

# Query returns contextual results
curl http://localhost:5000/api/search/markdown
# LLM generates blog posts about Markdown

curl http://localhost:5000/api/search/docker
# LLM generates blog posts about Docker

每种答复都是独特和现实的,符合查询要求。

形状控件 : 定义您的方案

除了生成随机数据之外, 您通常还需要精确控制 JSON 结构 。 形状控制可以让您告诉 LLM 确切地告诉 LLM 要生成什么结构 — 最强大的前端开发功能 。

基本形状基本形状

# Without shape - random structure
curl http://localhost:5000/api/mock/users
# Response: { "userId": 1, "fullName": "Alice" }

# With shape - you control it
curl "http://localhost:5000/api/mock/users" \
  -H 'X-Response-Shape: {"id":0,"name":"string","email":"string"}'
# Response: { "id": 1, "name": "Alice", "email": "[email protected]" }

指定形状的三种方式 :

  1. 查询参数 - ?shape={...}
  2. HTTP 信头 - X-Response-Shape: {...} (建议)
  3. 请求机构 - {"shape": {...}}

内嵌形状

const shape = {
  company: {
    id: 0,
    name: "string",
    employees: [{
      id: 0,
      firstName: "string",
      department: { id: 0, name: "string" },
      projects: [{ id: 0, title: "string" }]
    }]
  }
};

fetch('/api/mock/company', {
  headers: { 'X-Response-Shape': JSON.stringify(shape) }
});

类型Script 对齐

interface User {
  id: number;
  name: string;
  email: string;
}

const USER_SHAPE: Partial<User> = { id: 0, name: "", email: "" };

// Shape becomes your type definition AND mock schema!

具有背景背景的多阶段工作流量

现在让我们将形状控制与 API 环境结合起来处理复杂、多步骤的工作流程。 记得早些时候的上下文内存特征吗 ? 这是它如何在现实世界的无序操作中闪耀的。

例如,Mostlucid.net的翻译服务显示,LLM如何在整个同步工作流程中保持状态:

# Step 1: Start translation
curl -X POST http://localhost:5000/api/translate/start?context=translate-session \
  -d '{"language": "es", "markdown": "# Hello World"}'
# Response: { "taskId": "abc-123", "status": "processing" }

# Step 2: Check status (LLM remembers the task)
curl http://localhost:5000/api/translate/status/abc-123?context=translate-session
# Response: { "taskId": "abc-123", "status": "complete" }

# Step 3: Get result (same taskId!)
curl http://localhost:5000/api/translate/result/abc-123?context=translate-session
# Response: { "taskId": "abc-123", "translatedText": "# Hola Mundo" }

通知如何 taskId 所有要求均一致。 背景使这一点成为可能。

所有议定书

到目前为止,我们一直关注REST,但现代应用需要更多。无论你是与GreagQL一起建造,还是与信号R一起安装实时功能,还是与GRPC服务公司合作,大多数都是Lucid.mockllmapi由你负责。

支持的协议 :

  • 休息
  • 图表QL
  • GRPC 乡人民委员会
  • 信号
  • 服务器事件(SSE)
  • OpenAPI / 交换器

图QL

指南: 图图QL部分

curl -X POST http://localhost:5000/api/mock/graphql \
  -d '{"query": "{ users { id name email } }"}'

查询是形状 - 不需要单独的计划 。

GRPC 菲律宾菲律宾人民党

完整的指南 : gRPPC 支持

# Upload .proto file
curl -X POST http://localhost:5116/api/grpc-protos \
  --data-binary "@user_service.proto"

# Call via JSON or binary Protobuf
curl -X POST http://localhost:5116/api/grpc/userservice/UserService/GetUser \
  -d '{"user_id": 123}'

实时

指南: 信号R演示指南

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/hub/mock")
    .build();

connection.on("DataUpdate", (message) => {
    console.log(message.data); // Live generated data
});

await connection.start();
await connection.invoke("SubscribeToContext", "stock-prices");

完美的仪表板原型设计。

服务器- 服务器事件( SSE)

指南: SSE 流模式

const eventSource = new EventSource('/api/mock/stream/users');
eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Token:', data.chunk); // Progressive generation
};

OpenAPI / 交换器

完整的指南 : OpenAPI 特征

# CLI: Load any OpenAPI spec
llmock serve --spec https://petstore3.swagger.io/api/v3/openapi.json

# All endpoints become live mocks automatically
curl http://localhost:5000/petstore/pet/123

可排除工具: 混混 Real & Mock 数据

完整的指南 : 工具与动作

有时,您需要一种混合方法 — 生产中的真实数据与生成的模拟数据相结合。 插入工具系统允许您在模拟生成时使用实际的 API , 从而创建出令人难以置信的现实的测试情景 。

{
  "Tools": [{
    "Name": "getUserData",
    "Type": "http",
    "HttpConfig": {
      "Endpoint": "https://api.production.com/users/{userId}",
      "Headers": { "Authorization": "Bearer ${PROD_API_KEY}" }
    }
  }]
}
curl "http://localhost:5000/api/mock/orders?useTool=getUserData&userId=123"

模拟获取真正的用户数据,然后LLM生成使用它的命令。 对以混合模拟/实际工作流程进行现实测试极为有用。

ASP.NET 核心一体化

如果您正在与 ASP.NET 核心一起建设, 整合是无缝的。 这个方法的美丽之处在于 零代码修改 您的服务 - 简单配置 HttpClient 在开发过程中和生产的实际消费物价指数中指向模型。

// Real code from mostlylucid.net
builder.Services.AddHttpClient<IMarkdownTranslatorService, MarkdownTranslatorService>(
    client => {
        var baseUrl = builder.Configuration["TranslationService:BaseUrl"]
            ?? "http://localhost:5000";  // Mock during dev
        client.BaseAddress = new Uri(baseUrl);
    }
);

开发.json:

{
  "TranslationService": {
    "BaseUrl": "http://localhost:5000"  // Mock
  }
}

应用。 production.json:

{
  "TranslationService": {
    "BaseUrl": "https://api.production.com"  // Real
  }
}

此模式适用于任何 HttpClient 在您的申请中 - 翻译服务、付款网关、外部API, 您可点名 。

何时使用此功能

在我们潜入先进功能之前, 让我们先弄清楚这个工具 何时对你的工作流程有意义。

完美于 :

  • 后端存在前的前端开发 - 停止阻拦后端小队
  • 多步骤工作流程测试 - 内存处理复杂情况
  • API 原型 - 在承诺前先进行反应状态实验
  • 离线发展 - 没有网络依赖性的工作
  • 错误假设情况测试 - 模拟故障,不中断生产
  • CI/CD输油管 - 没有外部依赖意味着更快、更可靠的建筑

不理想的有:

  • 生产环境 - 这是一个开发和测试工具
  • 确定性测试数据 - 需要精确复制时使用固定装置
  • 合同测试 - 生产合同总是对真实的APPS进行验证

现在你知道它适合哪里了 我们来探索一下先进的能力

高级特征

这些特质是可选的 — — 你可以从基础中单独获得巨大的价值。 但是当你需要规模的生产级现实主义时,这些工具就在这里。

多个 LLM 后端

指南: 多个 LLM 后端

# Fast for dev
curl http://localhost:5000/api/mock/users

# High quality for demos
curl "http://localhost:5000/api/mock/users?backend=quality"

# Cloud AI for production-like
curl "http://localhost:5000/api/mock/users?backend=openai"

降速限制模拟

指南: 节率限制和节拍

测试您的应用程序如何处理利率限制 :

{
  "EnableRateLimiting": true,
  "RateLimitDelayRange": "500-2000"
}

模拟错误

# Test 429 rate limiting
curl "http://localhost:5000/api/mock/users?error=429&errorMessage=Rate%20limit%20exceeded"

# Test 503 unavailable
curl "http://localhost:5000/api/mock/users?error=503"

支持所有4xx和5xx代码。

反应缓存

# Generate and cache 10 variants
curl "http://localhost:5000/api/mock/users?shape={\"$cache\":10,\"id\":0,\"name\":\"string\"}"

随后的请求得到即时缓存答复。

测试公用事业:多数为lucid.mockllmapi。

套件 : 大多为mockllmapi。 测试

上述所有特征对于发展来说都是巨大的,但是自动化测试呢?配套测试软件包提供了流流利的API,使整合测试成为微风 — 配置模拟行为。 HttpClient 其余的做。

安装安装

dotnet add package mostlylucid.mockllmapi.Testing

基本使用率

using mostlylucid.mockllmapi.Testing;

// Create a client with a single endpoint configuration
var client = HttpClientExtensions.CreateMockLlmClient(
    baseAddress: "http://localhost:5116",
    pathPattern: "/users",
    configure: endpoint => endpoint
        .WithShape(new { id = 0, name = "", email = "" })
        .WithCache(5)
);

// Make requests - configuration is automatically applied
var response = await client.GetAsync("/users");
var users = await response.Content.ReadFromJsonAsync<User[]>();

多端点

var client = HttpClientExtensions.CreateMockLlmClient(
    "http://localhost:5116",
    configure: handler => handler
        .ForEndpoint("/users", config => config
            .WithShape(new { id = 0, name = "", email = "" })
            .WithCache(10))
        .ForEndpoint("/posts", config => config
            .WithShape(new { id = 0, title = "", content = "", authorId = 0 })
            .WithCache(20))
        .ForEndpoint("/error", config => config
            .WithError(404, "Resource not found"))
);

// Each endpoint automatically uses its configuration
var usersResponse = await client.GetAsync("/users");
var postsResponse = await client.GetAsync("/posts");
var errorResponse = await client.GetAsync("/error"); // Returns 404

配置选项

形状配置 :

// Using anonymous objects
.WithShape(new { id = 0, name = "", active = true })

// Using JSON strings
.WithShape("{ \"id\": 0, \"name\": \"\", \"tags\": [] }")

// Complex nested structures
.WithShape(new
{
    user = new { id = 0, name = "" },
    posts = new[] { new { id = 0, title = "" } }
})

错误模拟 :

// Simple error
.WithError(404)

// With custom message
.WithError(404, "User not found")

// With details
.WithError(422, "Validation failed", "Email address is invalid")

串流 :

// Enable streaming with token-by-token output
.WithStreaming()
.WithSseMode("LlmTokens")

// Stream complete objects
.WithStreaming()
.WithSseMode("CompleteObjects")

// Stream array items individually
.WithStreaming()
.WithSseMode("ArrayItems")

依赖性注射

输入的客户端 :

services.AddMockLlmHttpClient<IUserApiClient>(
    baseApiPath: "/api/mock",
    configure: handler => handler
        .ForEndpoint("/users", config => config
            .WithShape(new { id = 0, name = "", email = "" }))
);

命名客户端 :

services.AddMockLlmHttpClient(
    name: "MockApi",
    baseApiPath: "/api/mock",
    configure: handler => handler
        .ForEndpoint("/data", config => config
            .WithShape(new { value = 0 }))
);

// Usage
var client = httpClientFactory.CreateClient("MockApi");

融合测试示例

[Fact]
public async Task Should_Handle_User_Creation()
{
    // Arrange
    var client = HttpClientExtensions.CreateMockLlmClient(
        "http://localhost:5116",
        "/users",
        config => config
            .WithMethod("POST")
            .WithShape(new { id = 0, name = "", email = "", createdAt = "" })
    );

    // Act
    var newUser = new { name = "John Doe", email = "[email protected]" };
    var response = await client.PostAsJsonAsync("/users", newUser);

    // Assert
    response.EnsureSuccessStatusCode();
    var created = await response.Content.ReadFromJsonAsync<User>();
    Assert.NotNull(created);
    Assert.NotEqual(0, created.Id);
}

[Fact]
public async Task Should_Handle_Not_Found_Error()
{
    // Arrange
    var client = HttpClientExtensions.CreateMockLlmClient(
        "http://localhost:5116",
        "/users/999",
        config => config.WithError(404, "User not found")
    );

    // Act
    var response = await client.GetAsync("/users/999");

    // Assert
    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

如何运作

缩略 MockLlmHttpHandler 是 a 是 DelegatingHandler 并且:

  1. 拦截流出的HTTP请求
  2. 将请求匹配于已配置的端点模式
  3. 通过查询参数和 HTTP 信头输入模拟配置
  4. 将修改后的请求转发到实际模拟 LLM API

这允许您使用真实的 HttpClient 在测试中,在不修改应用代码的情况下,很容易控制模拟API行为。

最佳做法和提示

与这个工具合作后, 在多个项目中, 以下是最有效的模式:

  1. 工作流程总是使用环境 - 确保多步骤行动的身份证和数据的一致性
  2. 类型安全使用形状 - 使其匹配您的 TypeScript 接口
  3. 将真实和模拟数据与工具混合 - 最好的两个世界
  4. 选择正确的模型 (见 《奥亚马示范指南》 完整细节:
    • 为建议dev: ministral-3:3b (3B参数,32K上下文) - 杀杰森的凶手! 超快、高度准确、最低记录和档案管理
    • 类似生产: llama3 (8B参数,8K上下文) -- -- 最佳质量和业绩平衡
    • 高质量: mistral-nemo (12B参数,128K上下文) -- -- 复杂模型和大型数据集
    • 资源有限: gemma3:4bphi3 - 较轻替代品

完整文件

结论 结论 结论 结论 结论

前端开发不需要等待后端 APIs。 mostlylucid.mockllmapi 给予您 :

  • 内存 - 跨越多阶段工作流程的一致、有条不紊的数据
  • 形状控制 - 与你们类型相匹配的精确计划定义
  • 支持世界普遍议定书 - STST、GregQL、GRPC、信号、SSE、开放API
  • 混合测试 - 将实际生产数据与制作的模型混合
  • 零维修零保养 - 没有JSON装置在需求改变时更新
  • 测试公用事业 - 一体化测试流利API

这与传统嘲笑的区别? 您的前端对从第一天开始的现实的、有背景意识的数据起作用。 没有更多的“它用模拟数据工作,但用真实数据失败了 ” 惊喜。

无论你正在建立一个简单的博客还是一个复杂的企业应用程序, 你都会更快速,更彻底地测试, 并且有信心地航行。

准备好开始了吗?

docker compose up -d

就是这样,不需要后端

Finding related posts...
logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.