Add swagger to an http trigger azure function
This article demonstrates how to add swagger support for an http trigger azure function.
Swagger is an open source set of rules, specifications and tools for developing and describing RESTful APIs. Swagger framework allows developers to create interactive, machine and human-readable API documentation.
Swagger provides tools for implementing OpenAPI Specification. The 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 through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.
Below steps covers how to enable swagger for http trigger function endpoints.
Create an azure function project
Create azure function project and install AzureExtensions.Swashbuckle NuGet package. I am using .Net 6 and azure function version v4.
Add http triggers for Swagger
Add http trigger functions to add support for Swagger UI and Swagger Json. Set authorization level to AuthorizationLevel.Anonymous if you want swagger endpoints to be available without any authorization. Add SwaggerIgnore attribute so that there endpoints are not part of swagger definition.
Add startup code for Swagger
Azure functions does not have Startup class (like .Net Core) by default so let’s add startup code to implement FunctionsStartup abstract class to configure swagger.
Add an http trigger function to test
Create an http trigger function for which you want to see API definition in swagger. If you don't want to enable API definition for an http trigger function, add SwaggerIgnore attribute.
Run the project
Run the project.
Swagger UI will be available at http://localhost:<port>/api/swagger/ui and Swagger Json document will be available at http://localhost:<port>/api/swagger/json. I my case port is 7024.
So we have successfully added swagger support for our http trigger azure function. Distribute the Swagger UI url to your clients/users to know the definitions of your http endpoints.
Link to github repository with sample code: https://github.com/iamsandeepkmr/FunctionAppSwagger
I hope this article helped you. Please clap if you liked it. Comment below for any queries or questions.
Cheers and happy learning!