0
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Net;
using System.IO;

namespace FunctionRestApi
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
    {

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("URL_with_client_id_authorization_token");
            httpWebRequest.ContentType = "application/json";

            httpWebRequest.Method = "GET";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
               var result = streamReader.ReadToEnd();
               log.LogInformation(result);
            }

            return new OkObjectResult(value: httpWebRequest);
      }
   }
 }

I am new to azure function. This code works when I am just using 'GET' method. But if I want to use 'POST' method with request body data i.e. date range (start_date and end_date) and some other sub_user_id, then how can I do that?

new_bie_new
  • 19
  • 1
  • 3

3 Answers3

0

See one of the answers in this SO question, it shows how to make a POST call using the HttpClient class, however it is creating new instance of it, it is not the right way. As a best practice use only a static object of HttpClient in your function app.

Anand Sowmithiran
  • 2,591
  • 2
  • 10
  • 22
0

first check with POSTMAN how you can connect to external API with what authentication configuration BASIC/ BEARER then you can write code using same configuration

Sarang Kulkarni
  • 367
  • 2
  • 6
0

Here is a simple example of a POST request using HttpClient with some comments:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace AzureFunctionsSandbox.Functions
{
    public static class Function1
    {
        private static readonly HttpClient _httpClient = new HttpClient();

        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest request,
            ILogger log)
        {
            // create request as an object to easily set values
            var myRequest = new MyRequest
            {
                StartDate = DateTime.Now,
                EndDate = DateTime.Now.AddDays(1),
                SubUserId = "ABC123"
            };

            // serialize to JSON string for POST request body
            var myRequestJsonBody = JsonConvert.SerializeObject(myRequest);

            // .PostAsync() requires a HttpContent object - StringContent is a sub class
            var requestContent = new StringContent(myRequestJsonBody, Encoding.UTF8, "application/json");

            // make the POST request
            var response = await _httpClient.PostAsync("URL_with_client_id_authorization_token", requestContent);

            // use response body for further work if needed...
            var responseBody = response.Content.ReadAsStringAsync();

            return new OkResult();
        }
    }

    public class MyRequest
    {
        [JsonProperty(PropertyName = "start_date")]
        public DateTime StartDate { get; set; }

        [JsonProperty(PropertyName = "end_date")]
        public DateTime EndDate { get; set; }

        [JsonProperty(PropertyName = "sub_user_id")]
        public string SubUserId { get; set; }
    }
}

https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0

Chris
  • 3,113
  • 5
  • 24
  • 46