Skip to content

Swagger and SwaggerUI

Ronald Johnson edited this page Dec 12, 2024 · 2 revisions

Swagger is used to provide a user interface to interact with the APIs in addition to documentation.

Swagger example

Below is an example of swagger providing information about an endpoint to be shown later to a developer via SwaggerUI:

group.MapGet("/{orgId:int}", async (int orgId, int currentPage, int pageSize, GirafDbContext dbContext) =>
            {
              try
              {
                  var skip = (currentPage - 1) * pageSize;

                  var pictograms = await dbContext.Pictograms
                      .Where(p => p.OrganizationId == orgId || p.OrganizationId == null)
                      .Skip(skip)  
                      .Take(pageSize)  
                      .Select(p => p.ToDTO())
                      .AsNoTracking()
                      .ToListAsync();
                

                return Results.Ok(pictograms);
              }
              catch (Exception)
              {
                return Results.Problem("An error occurred while retrieving pictograms.", statusCode: StatusCodes.Status500InternalServerError);
              }
            })
            .WithName("GetPictogramsByOrgId")
            .WithDescription("Gets all the pictograms belonging to the specified organization.")
            .WithTags("Pictograms")
            .RequireAuthorization("OrganizationMember")
            .Produces<List<PictogramDTO>>(StatusCodes.Status200OK)
            .Produces(StatusCodes.Status400BadRequest)
            .Produces(StatusCodes.Status500InternalServerError);

The methods

  • .WithName("GetPictogramsByOrgId")
    • The name of the endpoint shown in SwaggerUI
  • .WithDescription("...")
    • Description of the endpoint itself
  • .WithTags("Pictograms")
    • Endpoints that share a tag will be grouped together in SwaggerUI
  • .Produces<List<PictogramDTO>>(StatusCodes.Status200OK)
    • Shows the type of data returned along with a 200 success code
    • Similarily the .Produces(StatusCodes.Status400BadRequest)shows that another possible response from this endpoint is a bad request code

Authenticating within SwaggerUI

After successfully using the login endpoint, a token will be provided in the response. Copy this token and click the green "Authorize" button with a little lock at the top right of the page. Paste the following into the opened dialog's field

Bearer {token_received_from_login_endpoint}

The token will then be added to the header with each request sent from SwaggerUI, allowing access to endpoints behind authentication.

Clone this wiki locally