0% found this document useful (0 votes)
23 views8 pages

SIT331 5.1P TaskSheet

This document outlines the requirements and instructions for implementing OpenAPI documentation for a Web API as part of a practical task. It emphasizes the importance of clear documentation for maintainability and provides detailed steps for setting up OpenAPI using the Swashbuckle library, including customizing the UI and enabling XML comments for auto-documentation. The submission process includes testing the program, ensuring all endpoints work correctly, and submitting specific files to OnTrack by the given deadlines.

Uploaded by

bhuwank301
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views8 pages

SIT331 5.1P TaskSheet

This document outlines the requirements and instructions for implementing OpenAPI documentation for a Web API as part of a practical task. It emphasizes the importance of clear documentation for maintainability and provides detailed steps for setting up OpenAPI using the Swashbuckle library, including customizing the UI and enabling XML comments for auto-documentation. The submission process includes testing the program, ensuring all endpoints work correctly, and submitting specific files to OnTrack by the given deadlines.

Uploaded by

bhuwank301
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Task_5.1P.

md 2025-03-20

Practical task 4.1


(Pass/Credit Task)
Documentation
Submission deadline 23 59 Sunday, Sep 4; Demonstration deadline 23 59 Sunday, Sep 18
General Instructions
Clear and concise documentation throughout the development process is crucial for the maintainability of
software. It is essential in Open/Host Services in terms of Domain-Driven Design as this system is highly
decoupled and reusable; therefore, many people can use it.
By the time you have a working prototype, you want to have at least some form of documentation.
Generally, even the Aggregate Design Canvas from 2.1P is part of the documentation as it is a form of
Software Requirements Specification.
In this task, you will implement an OpenAPI Documentation for your Web API. OpenAPI Specification
(OAS) defines a standard, language-agnostic interface to RESTful APIs, which allows both humans and
computers to discover and understand the capabilities of the service without access to source code,
documentation, or network traffic inspection.
Learning goals
The goal is to learn tools and techniques that provide documentation to the backend service. OAS provides
a straightforward way to add documentation to users of the API as well as the developers who work on
maintaining it. You will also learn to use XML Documentation Comments, a matured documentation API
used in the legacy system presented in 3.2P. It can be used not only in web development.
There are multiple different documentation generators that you can explore as an optional part of this task.
Among those are DocFX, Sandcastle, Doxygen. You can find some additional sources in the optional part
of the Additional Materials.
Technology Stack Requirements
Please refer to the Additional Materials to learn more about OpenAPI Specification and a tutorial on
implementing it in ASP.NET. In this particular task, we will use a library called Swashbuckle to add
automatic documentation.
Installation and Setup
First, copy the robot-controller-api folder from the previous week solution folder to 5.1P so you can
compare the changes between previous tasks and this one.
Open terminal in your robot-controller-api folder and run:

dotnet add package Swashbuckle.AspNetCore --version 6.5.0


1/8
Task_5.1P.md 2025-03-20

It modifies the project file and adds a reference to a Swashbuckle library to it.
robot-controller-api.csproj:

...
<PackageReference Include="Npgsql" Version="9.0.2" />
+ <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
...

To start using Swashbuckle, you need to enable the generation of the OAS file so that it can be used to
show the proper documentation in the UI. It is done in the Program.cs file by adding the following piece of
code after builder.Services.AddControllers(); line:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

Then we need to instruct the application to use the OpenAPI specification file and the UI for it by adding the
following code after the app is built (so after var app = builder.Build();).

app.UseSwagger();
app.UseSwaggerUI();

Suppose you want OpenAPI UI and OAS to be available only for the development environment and not be
exposed on production. In that case, you need to check app.Environment.IsDevelopment() and add
the last piece of code only if it is true.
After you have enabled OpenAPI for your web API, run the program, go to the browser, and check the
https://localhost:7166/swagger URL to see whether your API is shown there. On this page you find
a link to swagger.json that holds your OAS schema file that you will need to submit to OnTrack.
Ensure you use the correct port number that corresponds to your application.
Coding Requirements and Instructions
Customizing the UI
First, let's personalize our web API UI by changing the default UI theme and substituting the default
Swagger logo in the top right corner.
Bringing the Resources
There is a way to change the style of the API documentation page by injecting a different stylesheet instead
of the default one. We will build upon existing free open-source themes developed by Mark Ostrander that
2/8
Task_5.1P.md 2025-03-20

you can find in the task archive or download directly from Free Open-Source Swagger UI Themes.
To use stylesheets and logos, we need a wwwroot folder in our project structure. All static files in your
project go into this folder. These are assets that the app will serve directly to clients, including HTML files,
CSS files, image files, and JavaScript files. The name of the folder comes from a convention shared across
different platforms.
Create a wwwroot folder in your robot-controller-api folder, then create these folders inside of
wwwroot:

images
styles
swagger .
From the downloadable task resources, put CSS files into styles and deakin-logo.png into images.
You can also get the Deakin logo directly from the Deakin website by right-clicking and saving it on your
local machine. For the smaller icon (favicon) shown next to the web API in the browser tab, you can
generate your favicon from the logo using Favicon Converter or download prepared favicons from the task
resources. They should be in the swagger folder inside the wwwroot folder.

📦 wwwroot
┣ 📂 images
┃ ┗ 📜 deakin-logo.png
┣ 📂 styles
┃ ┣ 📜 robot.css
┃ ┣ 📜 theme-feeling-blue.css
┃ ┣ 📜 theme-flattop.css
┃ ┣ 📜 theme-material.css
┃ ┣ 📜 theme-monokai.css
┃ ┣ 📜 theme-muted.css
┃ ┣ 📜 theme-newspaper.css
┃ ┗ 📜 theme-outline.css
┣ 📂 swagger
┃ ┣ 📜 favicon-16x16.png
┃ ┣ 📜 favicon-32x32.png
┃ ┗ 📜 favicon.ico

robot.css in the previous directory structure block is a common stylesheet between all themes with the
following content:

.swagger-ui img {
content: url("/images/deakin-logo.png");
}

.swagger-ui .topbar .download-url-wrapper .select-label select {


border-color: #EF1C25;
}

.swagger-ui .info .title small:last-child {

3/8
Task_5.1P.md 2025-03-20

background-color: #EF1C25 !important;


}

... and it should be imported into each theme by adding:

@import url("robot.css");

at the top of every theme CSS file.


This way, you can easily put the shared CSS code in one file and switch between themes without rewriting a
lot of code.
Enabling Themes
Once your folder structure is ready, you need to enable UI customization in the C# code by enabling static
file usage and injecting an appropriate stylesheet into the OpenAPI UI.
This is done in Program.cs. First, add the following line of code to enable static file usage (CSS, favicons,
images from the wwwroot folder):

app.UseStaticFiles();

Next, use an overloaded version of UseSwaggerUI() and pass another void function into it as a parameter.
You find this out by exploring the UseSwaggerUI() signature that has an optional parameter of type
Action<SwaggerUIOptions> setupAction. Action is one of the predefined generic delegates that
describes a void function. If you see Action, Func or Predicate type of the parameter, it shows that
lambda expressions (anonymous functions) can be used as parameters.

Substitute the app.UseSwaggerUI(); with:

app.UseSwaggerUI(setup => setup.InjectStylesheet("/styles/theme-


flattop.css"));

You can use any theme from the styles folder; theme-flattop.css is just an example. Try different
themes to see which one you prefer the most.
Those changes should be sufficient to enable customization for your web API UI. It also provides a quick
test of your API endpoints using a web browser instead of a HTTP client like Postman.
If you still see an old green favicon from Swagger, you need to hard reload the web page to empty the
cache as the browser caches favicons, and you won't see an immediate effect after adding new favicons to
your page.
Before After
4/8
Task_5.1P.md 2025-03-20

Before After

For those who want some extra credit for their 1.3D task, you can work on creating your own OpenAPI
theme that your peers might find helpful. For example, I would love to see the theme representing Deakin
brand colors that you can get off the Deakin website.
Creating your theme is optional for this task.
Filling the Documentation
Authorship
Following a similar approach from the previous section, we will pass a lambda expression (anonymous
function) as a configuration function into our documentation generation methods in Program.cs.
Substitute builder.Services.AddSwaggerGen(); with:

builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo

5/8
Task_5.1P.md 2025-03-20

{
Title = "Robot Controller API",
Description = "New backend service that provides resources for the
Moon robot simulator.",
Contact = new OpenApiContact
{
Name = "Max Slavnenko",
Email = "[email protected]"
},
});
});

Set the correct Name and Email.


XML Comments for Auto-Documentation
Enabling XML comments in your code provides auto-documentation into OpenAPI and, on top of that, adds
hints into the Intellisense feature of your IDE.
To enable XML comments, modify the robot-controller-api.csproj file and add:

<Project>
...
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
...
</Project>

If you don't suppress compiler 1591 warnings, you will get a warning for every public method that doesn't
have an XML comment section. It is a good practice to provide XML comments for your code.
Next, you need to generate a XML comments file and pass it into the OpenAPI generator so that it can get
the comments out and use them in the documentation API. Add the following code inside the
AddSwaggerGen delegate inside the Program.cs file:

var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";


options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory,
xmlFilename));

It also requires adding using System.Reflection; at the top of the file.


Once the XML comments are enabled, you can add them to every endpoint in your API. Here is an example
of the comment for the creation of the robot command:

6/8
Task_5.1P.md 2025-03-20

/// <summary>
/// Creates a robot command.
/// </summary>
/// <param name="newCommand">A new robot command from the HTTP
request.</param>
/// <returns>A newly created robot command</returns>
/// <remarks>
/// Sample request:
/// POST /api/robot-commands {
/// "name": "DANCE",
/// "isMoveCommand": true,
/// "description": "Salsa on the Moon"
/// }
///
/// </remarks>
/// <response code="201">Returns the newly created robot
command</response>
/// <response code="400">If the robot command is null</response>
/// <response code="409">If a robot command with the same name already
exists.</response>
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
[HttpPost]
public IActionResult AddRobotCommand(RobotCommand? newCommand)
{
if (newCommand == null) return BadRequest();
...

Please follow the tutorial from the Additional Materials called Get started with Swashbuckle and ASP.NET
Core and fill in all the comments for the rest of your endpoints.
Hint: if you type /// it will auto-create a template comment, to help speed up the process.
Submission Process
To get your task completed, you must finish the following steps strictly on time. Please ensure that your
program implements all the required functionality, is compilable, and has no runtime errors. Programs
causing compilation or runtime errors will not be accepted as a solution. You need to test your program
thoroughly before submission. Think about potential errors where your program might fail.
Submission
Ensure that all endpoints have been tested, and are successfully interacting with your database.
Submit to OnTrack:
Program.cs - the settings of your program after you have implemented the documentation
robot-controller-api.xml - XML comments generated from your source code. It can be
found inside the bin folder in your solution.
swagger.json - OpenAPI specification generated by your program.
7/8
Task_5.1P.md 2025-03-20

Demonstration
Please answer any additional questions that the teaching staff might ask during the active class or in
OnTrack. Answering questions is part of the assessment procedure and is critical for your
understanding of the unit material.
Additional materials
. OpenAPI Specification
. Get started with Swashbuckle and ASP.NET Core
. Free Open-Source Swagger UI Themes
. XML Tags for C# Documentation
. Use Web API Conventions
. *DocFX - optional
. *Sandcastle Help File Builder - optional
. *Doxygen - optional

8/8

You might also like