OpenAPI Specification مش Swagger UI
OpenAPI Specification ملف machine-readable يصف HTTP API: paths/operations، parameters، request bodies، responses، schemas، security schemes، tags، servers. Swagger اسم ecosystem أدوات؛ Swagger UI مجرد واجهة تفاعلية تعرض OpenAPI document وتسمح بتجربة requests. وجود UI لا يعني بالضرورة أن العقد موثق جيداً.
ASP.NET Core 10 يوفر document generation عبر Microsoft.AspNetCore.OpenApi و AddOpenApi/MapOpenApi. واجهة Swagger UI أو Scalar هي أدوات منفصلة تستهلك JSON document. تحقق من package versions وخيارات hosting؛ لا تفترض أن UI تأتي تلقائياً مع built-in generator.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddOpenApi();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi(); // commonly /openapi/v1.json
}
app.MapControllers();
app.Run();OpenAPI Specification vs Swagger UI
OpenAPI document هو machine-readable description للـ HTTP API: servers، paths، operations، parameters، requestBody، responses، schemas، security schemes، tags، و components. Swagger UI مجرد viewer/test console يعرض document ويسمح بإرسال requests. ممكن تستخدم Redoc أو Scalar أو code generators من نفس OpenAPI document؛ الوثيقة هي العقد، والواجهة أداة عرض.
OpenAPI لا يثبت أن implementation مطابق للوثيقة. لو كتبت response schema يدويّاً ثم endpoint يرجع fields مختلفة، عندك contract drift. قلل drift بتوليد metadata من endpoint signatures/attributes، واختبر الوثيقة أو contract في CI.
المستوى المطلوب من OpenAPI
تقدر تشرح OpenAPI document و Swagger UI، وتوثق paths/parameters/request/response schemas/status codes/security/examples/versioning. تعرف أن document يمكن استخدامه لتوليد SDK، وأن SDK يعتمد على schema stability. وتعرف أن docs لا تحمي endpoint، وأن CI يجب أن يتحقق من صحة contract ويكشف breaking changes.
Endpoint Documentation و Schemas و Status Codes
كل operation ينبغي أن توضح summary/description، parameters ومكانها ونوعها، request schema و required fields، response schemas لكل status مهم، content types، examples واقعية، وهل endpoint deprecated. لا تكتفِ بأسماء مثل string/string؛ اشرح constraints والوحدات والـ formats.
[HttpPost]
[ProducesResponseType<ProductResponse>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<ActionResult<ProductResponse>> Create(
[FromBody] CreateProductRequest request,
CancellationToken token)
{
var created = await service.CreateAsync(request, token);
return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
}Attributes مثل ProducesResponseType تُعلن metadata. تأكد أن الاختبارات تثبت أن implementation يلتزم بها؛ document قد يكون inaccurate لو implementation يتصرف بطريقة مختلفة.
Schemas و Parameters و Responses
لكل operation وثّق operationId ثابت، summary/description، route/query/header parameters، request body media types، response status codes، schema لكل response، examples، tags، و deprecation إذا لزم. Schema يصف required fields و types/formats/enums/nullability. لا تخلط nullable مع optional: property قد تكون موجودة بقيمة null أو قد تكون غائبة تماماً حسب schema/serializer.
[HttpPost]
[ProducesResponseType<ProductResponse>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<ProductResponse>> Create(
CreateProductRequest request, CancellationToken token)
{
var created = await service.CreateAsync(request, token);
return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
}وثّق failure responses المهمة، مش 200 فقط. العميل يحتاج يعرف validation error shape و401/403 و404 و409 و429. لا تكتب response code في docs غير ممكن فعلياً من endpoint أو middleware.
OperationId و Tags و Schema Naming
OperationId ينبغي أن يكون unique ومستقراً لأن SDK generators قد تستخدمه كاسم method. Tags تجمع operations حسب resource/feature. Schema names ينبغي أن تكون واضحة ومميزة؛ لا تجعل request و response models مختلفة تشترك في schema name ملتبس. لو غيرت naming convention فجأة قد تتغير generated client APIs حتى لو HTTP contract لم يتغير.
راجع document الناتج فعلياً، لا تعتمد على source attributes فقط. تأكد من path templates و query parameter required flags و nullable schemas و error responses و security requirements. OpenAPI linting في CI يمنع مشاكل naming والوثيقة الناقصة.
Authentication Documentation و JWT Bearer
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer((document, context, cancellationToken) =>
{
document.Components ??= new OpenApiComponents();
document.Components.SecuritySchemes["Bearer"] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
In = ParameterLocation.Header,
BearerFormat = "JWT",
Description = "Paste the access token only; do not include the 'Bearer ' prefix."
};
return Task.CompletedTask;
});
});OpenAPI security scheme توثق كيف يرسل client credential؛ لا تنشئ JWT ولا تتحقق منه. لازم runtime authentication middleware و authorization policy موجودين فعلياً. لا تضع token حقيقي في OpenAPI examples.
JWT Bearer Security Scheme
OpenAPI security scheme يشرح للـ tooling أن API تستخدم HTTP bearer token. تقدر تضيف scheme باسم Bearer وتربطها بالـ operations أو document-wide security requirement. ده يخلي Swagger UI يظهر زر Authorize ويضيف Authorization header. لا تضع token حقيقي في generated document أو example.
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer((document, context, cancellationToken) =>
{
document.Components ??= new OpenApiComponents();
document.Components.SecuritySchemes["Bearer"] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "Paste an access token. Do not include the Bearer prefix."
};
return Task.CompletedTask;
});
});التفاصيل الدقيقة للـ transformer types تعتمد على Microsoft.OpenApi package version؛ استخدم snippet متوافق مع package المثبتة. تذكر أن توثيق Bearer لا يفعّل authentication ولا authorization في API؛ هو وصف للعقد فقط.
Try It Out و Generated SDK Safety
Swagger UI Try it out يرسل request حقيقي إلى API؛ لذلك لا تعرض production write operations بلا ضوابط. قدّم sandbox/test environment أو احمِ docs، وامنع حفظ secrets في shared browser. لا تعتبر Swagger UI مكاناً لإدارة tokens. Generated SDKs تحتاج مراجعة naming/nullability/error handling، واختبار request serialization و cancellation/timeouts.
في CI، قارن OpenAPI document بالنسخة السابقة واكتشف breaking changes مثل حذف field required أو تغيير type أو إزالة status response. وثّق deprecation و sunset. الوثيقة المفيدة جزء من developer experience و contract governance.
Public Docs vs Internal Docs
قد يكون عندك public API docs وأخرى internal. لا تعرض internal admin endpoints أو server topology أو sensitive examples بلا داعٍ. لكن تذكر أن إخفاء endpoint من OpenAPI ليس حماية؛ كل endpoint يجب أن يطبق authorization حتى لو غير موثق. يمكن حماية document endpoint نفسه أو نشره في developer portal منفصل.
أمثلة OpenAPI يجب أن تكون synthetic، لا تستخدم customer data أو real access tokens. Swagger UI Try it out قد ينفذ commands حقيقية؛ استخدم test environment أو احمِ operations الحساسة. وثّق destructive actions وتحذيراتها.
Versioning و Client SDK Generation
يمكن نشر OpenAPI document منفصل لكل API version، وإضافة deprecation metadata و migration notes. أدوات مثل NSwag و OpenAPI Generator يمكن أن تنتج client SDKs بلغات مختلفة. الـ generated client يقلل أخطاء كتابة URL/DTO لكنه لا يغني عن فهم HTTP failures و timeouts/retries/cancellation. راجع generated diff عند تغيير schema حتى لا تفاجأ بتغييرات breaking.
لا تفتح interactive API explorer في production بشكل تلقائي. إن احتجته، قيّد الوصول، أخفِ internal endpoints/secrets، ولا تعتبر إخفاء الوثائق بديلاً للحماية.
Versioning و SDK Generation
لو عندك v1 و v2، الأفضل أن يكون لكل version document واضح حتى العميل يختار contract المناسب. وثّق deprecated endpoints و sunset plan. Client SDK generation يحول schema إلى typed classes/methods في C#/TypeScript وغيرها، لكنه يعتمد على جودة document: operationId، nullability، enum names، date/time formats، و error schemas. لا تعتمد على generator من غير مراجعة الناتج وتجربة serialization.
احذر من تغيير response field من integer إلى string أو تغيير معنى enum value؛ ده breaking change حتى لو endpoint URL لم يتغير. وثّق compatibility policy في release process.
Generated SDK: ما الذي يجب مراجعته؟
بعد توليد SDK، راجع method names، nullability، enum handling، date/time types، cancellation support، error response types، auth token injection، و serialization defaults. جرب create/get/update flow على test API. SDK generation لا يصلح contract سيئاً؛ قد ينتج classes صالحة compile لكنها تتصرف بشكل غير متوافق مع server.
ثبت generator version في build pipeline حتى لا يتغير output بلا قصد. احتفظ بالـ generated code artifact أو اعمل generation reproducible. لو generated SDK public، schema changes قد تكون breaking حتى لو backend code changes تبدو بسيطة.
Breaking Changes في OpenAPI
Breaking change قد يكون حذف path أو method، حذف response field مطلوب، تغيير type/format، جعل field optional سابقاً required، تغيير enum semantics، تغيير auth requirement، أو حذف status response يعتمد عليه client. إضافة optional response field غالباً additive لكن بعض strict clients قد تتأثر. لا تعتمد على intuition؛ استخدم diff/linter ثم اختبر generated client.
خزن OpenAPI artifact لكل release/version. راجع diff في pull request، وحدد owner للـ contract. لو document generated من runtime، شغّل generation في CI بنفس configuration التي ستستخدم في production حتى لا تختلف servers/schemas.
Examples و Document Customization و CI
أضف examples واقعية لا تحتوي أسراراً، ووضّح nullable/required و formats و enum meanings و pagination envelopes. يمكن توسيع document transformers أو operation transformers لإضافة tags/descriptions/security metadata أو schema conventions. تجنب كتابة OpenAPI يدويّاً منفصل عن implementation إلا إذا كان contract-first هو المصدر المعتمد وتوجد عملية تحقق تمنع divergence.
في CI، أنشئ OpenAPI JSON لكل supported version وقارنها بالنسخة المنشورة باستخدام diff/breaking-change tooling. تغييرات إزالة field أو تغيير type أو حذف operation قد تكسر clients حتى لو compile server نجح. راجع SDK generation كجزء من contract review، وليس بعد release.
OpenAPI جيد يجعل client engineer يقدر ينفذ integration من غير قراءة source code: يعرف auth، parameters، constraints، success/error responses، examples، pagination، rate limits، و version lifecycle.
Examples و Parameter Documentation
كل parameter لازم يوضح source، type، required/optional، format، allowed values، default، bounds، و meaning. مثال pageSize من غير maximum مضلل؛ مثال date من غير timezone convention قد يسبب bugs. request/response examples يجب أن تكون realistic وغير حساسة، وتطابق schemas الفعلية. وثّق pagination links/cursors و error examples كذلك.
OpenAPI examples ليست test data تلقائياً؛ ممكن تكون invalid إذا تغير schema. الأفضل إعادة استخدامها في contract tests أو توليد fixtures منها عندما tooling يسمح. استخدم descriptions لشرح business semantics، لا تكرر اسم property فقط.
OpenAPI المدمج في .NET 9/10 مقابل Swashbuckle
من .NET 9، قوالب ASP.NET Core بقت بتستخدم Microsoft.AspNetCore.OpenApi المدمج لتوليد الـ document بدل Swashbuckle، ومن .NET 10 الـ document الافتراضي بقى OpenAPI 3.1 (JSON Schema 2020-12)، مع إمكانية إخراج YAML. الـ UI (Swagger UI أو Scalar) بقى اختيار منفصل عن التوليد.
builder.Services.AddOpenApi("v1", o =>
{
o.AddDocumentTransformer((doc, ctx, ct) =>
{
doc.Info = new() { Title = "Shop API", Version = "v1", Description = "Orders, catalog and billing" };
return Task.CompletedTask;
});
o.AddDocumentTransformer<BearerSecuritySchemeTransformer>(); // declare JWT bearer once for the whole document
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi(); // /openapi/v1.json (MapOpenApi("/openapi/{documentName}.yaml") for YAML)
app.MapScalarApiReference(); // optional UI package (Scalar.AspNetCore); Swagger UI is another option
}| Built-in (Microsoft.AspNetCore.OpenApi) | Swashbuckle / NSwag | |
|---|---|---|
| الصيانة | جزء من ASP.NET Core، بيمشي مع كل release | مكتبات مجتمع؛ لسه مستخدمة في مشاريع كتير قديمة |
| التخصيص | document/operation/schema transformers | filters ناضجة وأمثلة كتير |
| Build-time generation | مدعوم (Microsoft.Extensions.ApiDescription.Server) | مدعوم (CLI) |
| Migration | مش لازم تهاجر فورًا؛ الأهم إن الـ document صحيح ومراجع في CI | |
أسماء الـ APIs اتراجعت على release notes الخاصة بـ ASP.NET Core 10 بتاريخ 2026-11-18؛ راجعها مع نسختك.
توليد الـ document وقت الـ build وفحصه في CI
لو الـ document بيتولد بس وقت التشغيل، محدش هياخد باله إن PR غيّر الـ contract. الحل: ولّده وقت الـ build، احفظه في الـ repo، وقارن.
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" />
</ItemGroup>
<PropertyGroup>
<OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)/../../contracts</OpenApiDocumentsDirectory>
</PropertyGroup>- run: dotnet build src/Shop.Api -c Release # writes contracts/Shop.Api.json
- name: Fail on breaking changes
run: |
git show origin/main:contracts/Shop.Api.json > base.json
npx --yes oasdiff breaking base.json contracts/Shop.Api.json --fail-on ERR| تغيير | Breaking؟ |
|---|---|
| إضافة endpoint أو حقل اختياري في الـ response | لا (لو الـ clients بتتجاهل الحقول المجهولة) |
| حقل جديد required في الـ request | نعم |
| تغيير type حقل (int ← string) أو اسمه | نعم |
| إضافة قيمة enum في الـ response | غالبًا نعم لـ clients بـ strict enums (SDKs متولدة) |
| تغيير status code للنجاح (200 ← 201) | ممكن يكسر clients |
الربط: نفس الفكرة بشكل أقوى في Contract Testing (Pact) اللي بيختبر توقعات المستهلك الفعلية، مش بس شكل الـ schema.
من OpenAPI لـ Angular client typed
npx openapi-typescript contracts/Shop.Api.json -o src/app/api/schema.d.tsimport type { components } from './schema';
type OrderDto = components['schemas']['OrderDto'];
@Injectable({ providedIn: 'root' })
export class OrdersApi {
private http = inject(HttpClient);
list(page = 1) { return this.http.get<{ items: OrderDto[]; total: number }>('/api/orders', { params: { page } }); }
}
// Contract changes now surface as TypeScript compile errors in the frontend PR, not as runtime bugs.دي أبسط طريقة تربط الـ backend بالـ frontend من غير ما حد ينسخ interfaces بإيده. لو عايز client كامل (methods مش types بس)، أدوات زي Kiota أو NSwag أو openapi-generator بتعمل ده — بس الـ client المتولد لازم يتعامل كـ dependency: version، review، وما تعدلش فيه بإيدك.
أخطاء شائعة
- كشف Swagger UI في الإنتاج لـ API داخلي من غير auth — خريطة مجانية للمهاجم.
- Responses من غير status codes للأخطاء (400/401/403/404/409) فالـ SDK مش عارف يتعامل معاها.
- Anonymous objects في الـ responses: الـ schema بيطلع ضعيف أو فاضي. استخدم DTOs و TypedResults.
- OperationIds متغيرة تلقائيًا ← أسماء methods في الـ SDK بتتغير مع كل build.
- الثقة إن الـ document صح من غير ما حد يقراه: راجع diff الـ contract في كل PR زي الكود.
Knowledge check
PR أضاف حقل required جديد في request DTO. الـ CI بتاع الـ contract لازم يعمل إيه؟
ليه نخزن الـ OpenAPI document في الـ repo؟
Knowledge Check
هل Swagger UI هي نفسها OpenAPI Specification؟
هل إضافة Bearer security scheme تحمي endpoint؟
ما فائدة SDK generation وما خطره؟
OpenAPI في CI: اكتشاف Contract Drift
في CI شغّل التطبيق أو document generation، احفظ OpenAPI artifact، واعمل lint/validation. قارن document الحالي بالنسخة السابقة لاكتشاف breaking changes. اختبر أن كل operation لها operationId فريد، response schemas، tags، auth metadata، وأن الأمثلة صالحة. لا تكتفِ بفتح Swagger UI يدوياً قبل release.
في multi-version APIs، لا تجعل document يعرض endpoints من versions غير المقصودة. وفي production قرر هل public docs مفتوحة أم محمية، وهل تعرض internal endpoints. إخفاء docs ليس access control؛ endpoints نفسها لازم تكون محمية.
مراجعة OpenAPI كجزء من Code Review
راجع document كما يراه client: هل path names واضحة؟ هل verbs صحيحة؟ هل parameters required؟ هل pagination/filter/sort documented؟ هل response schema يطابق serialization؟ هل error responses موثقة؟ هل auth scheme مربوط بالـ operations المحمية؟ هل الأمثلة قابلة للتنفيذ؟ هل operationId stable؟
لو endpoint يرجع ProblemDetails لكن OpenAPI يظهر schema عام أو response ناقص، أضف metadata/transformer حسب framework. لا تكتب schema يدوي مختلفاً عن DTO. contract test يمكنه مقارنة document أو validate sample payloads against schema.
OpenAPI Quality Checklist
- Unique, stable operationId and useful tags.
- Accurate request body schema and content types.
- Required/optional/nullability documented correctly.
- All meaningful response status codes and schemas.
- Authentication scheme attached to protected operations.
- Examples valid and free of real secrets/PII.
- Pagination, filtering, sorting, و cursor semantics documented.
- Deprecation/versioning information visible.
- Document validated and diffed in CI.
OpenAPI is a contract artifact, not an API test and not an authorization mechanism. Keep generated documentation aligned with runtime behavior and review breaking changes before release.
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خريطة التغطية: 11 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.