在 API 准备前先建前端@ : @ non brittle sequits (中文 (Chinese Simplified))

在 API 准备前先建前端@ : @ non brittle sequits

Saturday, 13 December 2025

//

10 minute read

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

您有多少次被阻拦等待后端 APIs准备好@? @% 或花费小时来维护简陋的模拟数据,

输入 mostlylucid.mockllmapi @-@ a producation= - ready ASP}.NET核心模拟平台, 该平台使用大语言模型生成符合现实的 <, confirmedious API respected on the fly> @MS K4 而不是维持 JSON定着的{,}你得到智能模型来适应您的请求并记住所有调用中的状态.}

它支持什么 : 您需要的每个协议“-” REST,$GreakingQL,}gRPC},} gRPC}SignalRMS K4服务器{-} 伺服器}♪MSKSent Eprises ,}和 OpenAPI.}不同的静态定着@,}响应都是根据您的请求来动态生成的。 <%,} 建立多端-step工作流程及复杂的测试假想 polor_.

项目链接

Nuget 元数 Nuget 元数 GitHub 释放 驾照@: @unlisense

使用它的三种方法

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

  1. ASP.NET 核心 Nuget 软件包 “- 添加到您现有的项目中”
  2. 独立 CLI 工具 -Cross-platform 可执行程序 @(下载 释放)
  3. 嵌套容器 *- 需要零安装

Killer 特性@:上下文内存

📖}完整的指南 : APPI 背景文件

传统模拟API有致命的缺陷 @:每个请求都是独立的@. 获得一个具有 ID #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

法学硕士在同一背景下看待以前的请求,并生成一致的数据*. 这是用于 mount @ - step 工作流程@ MS K2} 的游戏+-changer

功能@: @%

寿命周期+:

  • “%15” 不活动分钟后自动过期@ ( @ configibable @ MS K2
  • 每次请求都会刷新计时器

行为=:

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

安全 :

  • 零内存渗漏@- 环境清理

使用案例@:

  • 完全适合 CI/}CD\ -}在运行中无状态

快速启动

选项 @1:_NuGet 软件包

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

CLI 工具

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

选项 @ 3:_% docker

完整指南=: docker 部署指南

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

LLM 后端

你需要 一号@ : Ollama,OpenAI,或L M StudioMS K3

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

见见 《奥亚马示范指南》 用于所有示范建议和比较的模型

立即尝试

一旦运行“ ,” , 您第一次请求“ I: ” 。 @ info/ plain

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

您现在有一个工作模拟API 生成现实的需求数据=.}

从 mostlucid\ .\ net 搜索真实的示例@ : @ 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 究竟要创建什么结构来生成\ MS K2 前端开发最强大的功能+.}

基本形状

# 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!

具有上下文的多端-+%Stencils

现在让我们 @ '%s 将形状控制与 API 上下文结合起来, 以处理复杂@ MS K1 mudi= -} step 工作流程@ MPK3 记住先前的上下文内存功能 < ? > Here{'_ 在现实中它是如何闪烁的吗? MSKO6world asynchronous operation@ I.}

由翻译服务提供的例子显示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, – 一起用SignalRMS K6 执行真实的- – 时间功能 或者与 GRPC 服务合作\ mostlucid+._mockllmapi 您是否覆盖了.–

支持的协议@: @%

  • 仅此而已
  • ✓ 图形QL
  • -=YTET -伊甸园字幕组=- 翻译:
  • ✓讯号
  • ✓伺服器-事件(SSEMS K3
  • @ ✓ @ OpenAPI @ I/ @ 斯瓦格

图QL

📖指南: 图图QL部分

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

查询是形状 @ -_ 不需要单独的方案@ MS K1\ {

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}'

信号Real=-}时间

📖指南: 信号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

可插件工具 @ :Mix 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使用它生成订单 对于使用混合模型进行现实测试极有用@/ @real 工作流程 @.#

ASP=.NET核心一体化

如果您使用 ASP+.NET Core@,#整合是无缝的 .}这个方法的美丽之处在于 零代码修改 - 您简单的配置 HttpClient 在制作过程中和生产中真实的API".

// 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
  }
}

appings .production.json}:#

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

此模式适用于任何 HttpClient 在您的应用程序中 {-} 翻译服务} ,} 支付网关@,} 外部APIs,} 您命名它<.> 。

何时使用此功能

在我们跳入高级功能前 @ , @ let@ MS K1 @ 清楚该工具何时对您的工作流程有意义\ .} @

完美地适合:

  • 后端存在前的前端开发 停止阻拦后端队
  • 多关- step 工作流程测试 - 内存处理复杂情景
  • API 原型 “- 实验,在承诺前有反应形状
  • 离线发展 工作没有网络依赖性
  • 错误假设情况测试 - 模擬失灵而不折断生产
  • CD管道 “-”没有外部依赖意味着更快的“,” 更可靠的建筑

不理想的:

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

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

高级特征

这些功能是可选的 @ -} 您可以从基本元素中获取巨大的价值@ MS K1 。 但是当您需要制作时, - page realismation 在比例上\ MPK3}这些工具在这里 @ I.}

多个 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"

降速限制模拟

📖指南: 节率限制 @ &_ _Batching

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

{
  "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"

支持所有 & M4 #%xx 和 < 5%x x code > @ .

反应缓存

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

随后的请求获得即时缓存回复@. @

测试工具@: @ mostlucid @ .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

配置选项

形状配置@ : @% 1

// 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")

依赖性注射

键入的客户端@: @% 1

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

命名客户端@: @% 1

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 {\fn黑体\fs22\bord1\shad0\3aHBE\4aH00\fscx67\fscy66\2cHFFFFFF\3cH808080}这

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

这允许您使用真实的 HttpClient 在测试中,在不修改应用程序编码的情况下 轻而易举地控制模拟API行为@. @%

最佳做法

此工具在多个项目中工作后 @ , @ 这里是最有效模式@ :} @

  1. 工作流程总是使用环境 -确保多@-# step 操作的标识和数据一致
  2. 类型安全使用形状 - 使其符合您的 TypeScript 接口
  3. 将真实和模拟数据与工具混合 最好的两个世界
  4. 选择正确的模型 (See( MSk0_ see) 《奥亚马示范指南》 完整详细信息@): @%
    • 为建议dev: ministral-3:3b @(3_B params@,} @ 32K上下文 @ I) @ @ MPK4 杀害杰森・马斯克的凶手 超精确的, 最小内存
    • 产量*-: llama3 @(8_B params@,}8_K 上下文 *)}{-}在质量和性能方面保持最佳平衡
    • 高质量: mistral-nemo (12_B params,}128K 上下文 @)}{-复杂图案和大型数据集
    • 资源@-_受限制: gemma3:4b 或 phi3 - 轻光替代品

完整文件

结论结论

前端开发 {'} 不必等待后端 APIs.} 。 mostlylucid.mockllmapi 已经给予您@: @%

  • 内存 - understand, 跨多@-step工作流程的状态数据
  • 形状控制 - 与您类型相匹配的精确计划定义
  • 支持世界普遍议定书 - REST, 圖表QLMS K2 gRPC, 信號RMSKO4 SSE}, OpenAPI
  • 混合测试 - 以生成的模型混合真实生产数据
  • 零维修 * - * 没有JSON固定装置可在需求改变时更新
  • 测试公用事业 - 用于集成测试的流利API

您的前端与现实的,}从一日起根据背景了解的数据有区别, 没有更多 "}它用模拟数据工作 但以真实的数据失败了 *"}惊喜=.}

您是否正在建立简单的博客或复杂的企业应用程序@ , @ 你'#lleverate faster\ ,}更彻底的测试 @ MS K4}和有信心的船舶=.}

准备开始?

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.