maui-rest-api

Guidance for consuming REST APIs in .NET MAUI apps, covering HttpClient configuration with System.Text.Json, dependency injection, service interface/implementation patterns, full CRUD operations (GET/POST/PUT/DELETE), error handling, platform plaintext-traffic configuration, and async/await best practices.

Last repository push
GitHub Stars
181
Forks
21
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "maui-rest-api" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-7b5818fb36dc758163ba2420da55fc4872150b31bcff93515687c83820c076b1. Verify the upstream source and version against https://github.com/davidortinau/maui-skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Guidance for consuming REST APIs in .NET MAUI apps, covering HttpClient configuration with System.Text.Json, dependency injection, service interface/implementation patterns, full CRUD operations (GET/POST/PUT/DELETE), error handling, platform plaintext-traffic configuration, and async/await best practices.

0 Downloads

Introduction source: third_party · davidortinau · 0.0.1 Reference

SkillPi interpretation

Tasks
// ✅ Register once in DI, inject everywhere builder.Services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("https://api.example.com") }); ```
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: maui-rest-api
description: >
  Guidance for consuming REST APIs in .NET MAUI apps. Covers HttpClient setup
  with System.Text.Json, DI registration, service interface/implementation
  pattern, full CRUD operations (GET, POST, PUT, DELETE), error handling,
  platform-specific clear-text traffic configuration, and async/await best practices.
  USE FOR: "REST API", "HttpClient", "call API", "GET request", "POST request",
  "API service", "JSON deserialization", "CRUD operations", "clear-text traffic",
  "consume API MAUI".
  DO NOT USE FOR: Aspire service discovery (use maui-aspire), authentication token handling
  (use maui-authentication), or local database storage (use maui-sqlite-database).

REST API Consumption — Gotchas & Best Practices

Common Mistakes

1. Creating HttpClient per request

// ❌ Creates socket exhaustion — each instance opens a new connection
public async Task<List<Item>> GetItemsAsync()
{
    using var client = new HttpClient();
    var response = await client.GetAsync("https://api.example.com/items");
    // ...
}

// ✅ Register once in DI, inject everywhere
builder.Services.AddSingleton(sp => new HttpClient
{
    BaseAddress = new Uri("https://api.example.com")
});

2. Blocking with .Result or .Wait()

// ❌ Deadlocks on the UI thread
var items = _apiService.GetItemsAsync().Result;

// ✅ Always use async/await
var items = await _apiService.GetItemsAsync();

3. Deserializing before checking status

// ❌ Tries to deserialize error HTML/JSON as your model
var content = await response.Content.ReadAsStringAsync();
var items = JsonSerializer.Deserialize<List<Item>>(content, _jsonOptions);

// ✅ Check status first
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var items = JsonSerializer.Deserialize<List<Item>>(content, _jsonOptions) ?? [];

4. Hardcoding BaseAddress in service methods

// ❌ Absolute URIs in every method — hard to change, easy to typo
await _httpClient.GetAsync("https://api.example.com/api/items");

// ✅ Set BaseAddress in DI, use relative URIs in methods
await _httpClient.GetAsync("api/items");

5. Missing error handling for network failures

// ❌ Crashes on network timeout, DNS failure, etc.
var items = await _apiService.GetItemsAsync();

// ✅ Catch both network and deserialization errors
try
{
    var items = await _apiService.GetItemsAsync();
}
catch (HttpRequestException ex) { /* network or HTTP error */ }
catch (JsonException ex) { /* malformed response */ }

Platform Pitfalls

⚠️ Clear-text HTTP blocked on emulators/simulators

Local dev servers on http:// are blocked by default. Configure exceptions:

  • Android: needs network_security_config.xml with cleartextTrafficPermitted="true" for 10.0.2.2
  • iOS/Mac Catalyst: needs NSAllowsLocalNetworking in Info.plist

⚠️ Android emulator uses 10.0.2.2 for localhost

The Android emulator maps 10.0.2.2 to the host machine. localhost refers to the emulator itself.

// ❌ On Android emulator, this hits the emulator, not your dev machine
new Uri("http://localhost:5000")

// ✅ Use the emulator's host loopback address
new Uri("http://10.0.2.2:5000")

iOS simulators use localhost directly.

⚠️ Inconsistent JSON casing

APIs typically use camelCase; C# properties are PascalCase. Without JsonSerializerOptions, deserialization silently returns default values.

// ❌ Properties stay null/default — no error thrown
JsonSerializer.Deserialize<Item>(content);

// ✅ Configure casing policy
private static readonly JsonSerializerOptions _jsonOptions = new()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    PropertyNameCaseInsensitive = true
};

Decision Framework

Scenario Error handling approach
Failure is unexpected (auth'd endpoints) EnsureSuccessStatusCode() — throws HttpRequestException
Need to branch on status codes Check IsSuccessStatusCode or response.StatusCode
Network may be unreliable (mobile) Wrap in try/catch for HttpRequestException
Response format may vary Also catch JsonException

Checklist

  • [ ] HttpClient registered as singleton or via IHttpClientFactory — never created per-request
  • [ ] BaseAddress set in DI; service methods use relative URIs
  • [ ] JsonSerializerOptions with CamelCase policy applied consistently
  • [ ] IsSuccessStatusCode or EnsureSuccessStatusCode() checked before deserializing
  • [ ] try/catch for HttpRequestException and JsonException in ViewModel calls
  • [ ] All API calls use async/await — no .Result or .Wait()
  • [ ] Service interface pattern used so ViewModels depend on abstractions
  • [ ] Android clear-text config for local dev (10.0.2.2)
  • [ ] iOS NSAllowsLocalNetworking for local dev

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value92/100

Highlights

  • 提供.NET MAUI应用中调用REST API的完整指南
  • 涵盖HttpClient配置、依赖注入、CRUD操作、错误处理等核心内容
  • 包含平台特定的明文流量配置和async/await最佳实践
Trigger Precision95/100

Highlights

  • 触发词定义清晰完整,覆盖多种相关场景
  • 明确排除了易混淆的相邻领域(如认证、本地数据库)
Structure and Standards85/100

Areas to improve

  • 缺少显式的'When to Use'章节 Reported severity: Minor

    虽然在frontmatter中描述了适用场景,但正文缺少独立的'When to Use'章节

    Recommendation: 建议在正文开头添加独立的'When to Use'章节,与'DO NOT USE FOR'形成呼应

  • 缺少端到端的完整项目示例结构 Reported severity: Minor

    提供了代码片段和最佳实践,但缺少完整的项目结构示例

    Recommendation: 建议添加一个完整的示例项目结构,展示服务接口、实现、ViewModel集成等

Highlights

  • 结构清晰,分章节组织内容
  • 每个常见错误都提供了错误示例和正确解决方案
  • 包含决策框架和检查清单,便于实践应用
Execution Reliability95/100

Highlights

  • 代码示例准确,遵循.NET MAUI最佳实践
  • 错误处理建议全面,覆盖网络异常和反序列化异常
  • 平台特定配置说明详细,可直接应用于实际开发
Evidence Verifiability (mean of the first four)92/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • 10.0.2.2
  • api.example.com
  • localhost

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.