Legion Developers

Sharing Knowledge

How To Make an API with Azure Functions and OpenAPI Support

Azure functions API

Hi guys, in this occasion I want to share how to create an API with azure functions to expose it as serverless functions.

The current version for visual studio at writing this post is 2022, so the next pictures are from that version.

The first step is create the azure function project in visual studio, to do this we should click on: File -> New -> Project, select Azure Functions and click Next.

Fill the data with your own information, and click next.

The next step is very important because at that moment, we should choose if we activate the OpenAPI support or not.

In Function dropdown choose Http trigger with OpenAPI and click Create.

Azure Functions with openapi support

After clicking create, the new project is ready to start coding, all the needed packages are installed by default through the azure functions template.

The default azure function created by template looks like:

[FunctionName("Function1")]
[OpenApiOperation(operationId: "Run", tags: new[] { "name" })]
[OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
[OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")]
public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
{
    _logger.LogInformation("C# HTTP trigger function processed a request.");
    string name = req.Query["name"];
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;
    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
        : $"Hello, {name}. This HTTP triggered function executed successfully.";
    return new OkObjectResult(responseMessage);
}

The main concepts for OpenAPI support are:

  • OpenApiOperation – This maps to “Operation Object” from the OpenAPI Specification.
  • OpenApiResponseWithBody – This maps to “Responses Object” from the OpenAPI Specification.
  • OpenApiParameter – This corresponds to “Parameter Object” from the OpenAPI Specification.
  • OpenApiSecurity – This corresponds to “Security Scheme Object” from the OpenAPI Sepcification.
How To Make an API with Azure Functions and OpenAPI Support

One thought on “How To Make an API with Azure Functions and OpenAPI Support

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top