Introduction: In the realm of modern APIs, the provision of clear and comprehensive documentation plays a pivotal role in facilitating developer adoption and ensuring efficient utilization. Swagger, aligned with the OpenAPI Initiative, stands out as a prominent solution, offering machine-readable documentation and a user-friendly interactive interface. In this guide, we'll delve into the seamless integration of Swagger into your .NET Core API. Step 1: Install the necessary packages Add Swashbuckle.AspNetCore NuGet package to a project: dotnet add package Swashbuckle.AspNetCore Add Swashbuckle.AspNetCore.SwaggerUI NuGet package to a project: dotnet add package Swashbuckle.AspNetCore.SwaggerUI Step 2: Add services in program.cs In the program.cs file, include the following service additions: builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); Additionally, add middleware in program.cs to enable Swagger in the development environment: if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } Step 3: Run the API project and access the Swagger UI at: https://your-api-base-url/swagger Ensure the API project is running, and navigate to the provided URL to explore and interact with the Swagger UI seamlessly. Step 3: Execute the APIs and test.
In this blog, I will be sharing insights on how to effectively manage Conditional Authorization and Swagger Customization. Case 1 I'm currently working on a problem our QA team found while testing our website. Specifically, there's an issue with one of the features in the application that uses an API. In the QA environment, we need to allow access without authentication, but in the production environment, authentication is required. To fix this, I added a feature called Conditional Authorize Attribute with help of Environment Variable. This feature lets us control access to the API based on the environment. It allows anonymous access when necessary. In my situation, I've added a environment variable setting called "ASPNETCORE_ENVIRONMENT" to "QA" in the testing site's pipeline. Because of this, I can use the API on the QA server without requiring authentication. This method also helps specific authorization rules for the API based on the environment. Case 2 Additionally, I've added Swagger requests into a value object to meet specific requirements on swagger. By extending the Swashbuckle Swagger IOperationFilter, I integrated logic tailored to our needs. This approach allows us to customize requests in Swagger for all APIs directly. Furthermore, I've implemented a middleware designed to handle responses and here's how it works. In my case, there are three kinds of response class in my code that specify the response type (like ApiErrorResponse, ValidatorResponse, ResponseModel). According to the requirements, when we get a 200-status code with the correct response class model, I need to wrap the response object in a value format. I created a middleware for this. It figures out which endpoint we're dealing with through the HttpContext. Using that endpoint, I grab the metadata related to the ProducesResponseTypeAttribute class and check for a status code of OK (Metadata Extraction). If I manage to get the metadata with a status code of 200, I include that response in value format. Otherwise, I stick with the same model response. This helps you to modify the response as per needed outcome. These implementations provide a flexible solution for conditionally authorizing API access and wrapping request/response in an object according to specified requirements.
For their software systems, most of the companies are moving towards microservices models. This suggests that separate datastores and separate commands for dealing with that datastore will be available in various parts of their programme. Microservices attract software providers because they allow software modules to be implemented more quickly; when one part of an application is modified, it is possible to continue to work in the other areas of the application. Most of the microservices use Application Programming Interfaces (APIs); API is a series of commands about how a function can be used. And most APIs use Hypertext Transmission Protocol (HTTP) requests for Representational State Transfer (REST) to request and submit data. So, let’s dive deeper and see what is API and API Testing and understand the different criteria of API Testing: What is the Application Programming Interface (API)? Application Programming Interface (API) is a computer interface that allows 2 different software systems to communicate and share data. The software framework running an API requires many functions/subroutines that can be handled by another software system. The API specifies requests that can be made between two software systems, how to send requests, data formats that can be used, etc. What is API Testing? API TESTING is a method of software testing that validates APIs. The aim of API Testing is to verify the programming interfaces' accessibility, compatibility, performance, and security. In API Research, you use tools to send calls to the API, get output, and write down the system's response instead of using normal user inputs(keyboard) and outputs. API Tests are somewhat different from GUI Tests and won't rely on an application's look and feel. Cases when API Testing should be checked: Return value dependent on input condition - Because input can be specified and results can be authenticated, it is reasonably easy to verify. Do not return anything - If there is no return value, verify the action of the API on the device. Cause any other API/event/interrupt - If any event or interrupt is triggered by an API entry, these events and interrupt listeners should be tracked. Data structure update - The device will have an output or effect on the data structure update, and it should be authenticated. Modify certain resources - If the API call modifies certain resources, it should be checked by accessing the respective resources. API Testing Methodology: QA Team performs the predefined approach i.e. API Testing Methodology in order to conduct the API testing after the build is ready. API Testing does not involve source code. The method of API testing helps to better understand the functionalities, testing methods, feedback criteria and test case implementation. Following are the points that encourages the user to take API Testing Methodology: Understanding the API program's capabilities and specifically describing the program's reach . Apply testing methods such as classes of equivalence, study of boundary value, and API error guessing and writing test cases. Input API parameters need to be adequately designed and specified. Run the test cases and compare the outcomes predicted and actual. API Testing Steps: Testing for API Automation should cover at least the following test methods, rather than the normal SDLC procedure: Discovery Testing: The test group can carry out the collection of calls documented in the API manually, such as checking that it is possible to list, build and uninstall a particular resource exposed by the API as necessary. Usability Checking: This testing verifies whether the API is user-friendly and usable. And the API also interacts well with other platforms. Security Monitoring: This testing concerns the form of protection needed and if confidential data is encrypted over HTTP or both. Automated Testing: API testing can result in a series of scripts or a method that can be used daily to run the API. Documentation: To communicate with the API, the research team needs to make sure that the documentation is sufficient and contains enough detail. Documentation should be used in the final deliverables Following is the best practices for API Testing: The API test cases can be classified by the types of tests. You should have the declarations of the APIs being named on top of each test. In the test case itself, parameter selection should be specifically stated. Prioritize calls to the API feature so that testers can test quickly. Each test case should be as autonomous and isolated as possible from dependencies. Following are the types of bugs that API Testing can detect: Fails to manage error situations. Duplicate or incomplete features. Durability issues. Difficulty in linking and receiving an API reply. Safety issues. Issues of multi-threading. Efficiency issues. Very high API response time. Inappropriate mistakes/warning to a caller. Following are the main challenges of API Testing: Parameter Combination, Parameter Collection, and Call Sequencing are the key problems in Web API testing. No Interface is available for checking the programme, making it impossible to have input values. It is necessary for testers to know the Collection and categorization of parameters. It is important to verify the exception handling feature. For testers, coding expertise is important. Benefits of API Testing: Access to an application without User Interface. Protection from malicious code and breakage. Cost-Effective. Reduces Testing Cost. Technology Independent. Conclusion - API Testing is a fundamental part of API development and is considered to be a challenging part of software testing. The API consists of a collection of classes/functions/procedures describing a layer of business logic. If the API is not properly checked, not only the API application, but also the calling application can cause problems. PS - By joining hands with MagnusMinds for API Testing services, you’re ensuring that you’ll get the best of the API Testing Services. Our simple and foundational approach to API Testing is to develop a dynamic and robust research strategy. At the initial level, we group all test cases depending on the type of the test. After that for the most predicted and highly normal effects, we first perform research. We delegate API method calls to goals, making the whole testing process smoother and faster. We guarantee checking for failure to provide you a smooth software that gives reliable performance.