Home > front end >  Call a GET API in Azure Function with Parameter
Call a GET API in Azure Function with Parameter

Time:12-20

I am trying to implement an Azure Function that will take ID as the input and retrieve the data according to that ID. Basically, the Azure function will call another API and it will get the data from it. I facing the issue where I cannot pass the ID as a parameter.

API (.NET)

[HttpGet]
        [Route("{id:guid}")]
        public async Task<IActionResult> GetContact([FromRoute] Guid id)
        {
            var contact = await dbContext.Contacts.FindAsync(id);

            if (contact == null)
            {
                return NotFound();
            }

            return Ok(contact);
        }

Function

[FunctionName("GetSingleContact")]
        public async Task<IActionResult> GetContact(
            [HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Get), Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {

                var client = _httpClientFactory.CreateClient();
                string id = req.Query["id"];//Null
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                id ??= data?.id;

                HttpResponseMessage httpResponseMessage = await client.GetAsync($"https://localhost:7209/api/Contacts/{id}");

                if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var content = httpResponseMessage.Content;
                    var data1 = await content.ReadAsStringAsync();
                    return new OkObjectResult(data1);
                }

            }
            catch(Exception ex)
            {
                return new BadRequestObjectResult(ex.Message);
            }
            
            return new BadRequestObjectResult("Problem");
        }

Every time I pass the ID it will be null. What is happening here?

CodePudding user response:

It should works in the http trigger by setting route parameters like this:

[FunctionName("GetSingleContact")]
public async Task<IActionResult> GetContact(
            [HttpTrigger(AuthorizationLevel.Anonymous, 
            nameof(HttpMethods.Get), Route = "{id}")] HttpRequest req, 
            string id,
            ILogger log)
{
 //use the id
}

For more details, please read this: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=in-process,functionsv2&pivots=programming-language-csharp#customize-the-http-endpoint

  • Related