REST API Consulting another API

Asked

Viewed 213 times

0

I need to make a REST API, which would query data from a cloud API, and return in the app in json format, but even with a lot of research, I didn’t find anything like it, I just wanted to know how I could do for the REST API I create to access the data that is already in this cloud API.

Ps: I am doing the API in . Net Core

  • An api "in . Net core" does not differ from other applications to make http requests. Take a look at this link (in English) with some important information https://docs.microsoft.com/en-us/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

1 answer

1

Your question is vague, but I will illustrate a way to do this, in the example I will assume that you can connect and consume this cloud API since you did not mention having doubts in it.

Briefly just create a method normally in your API, and within this method you make the request in the desired API. If you have parameters pass the parameters to your API and then use them in the Cloud API call.

You would create a method like this in your API:

    private object GravarLogAPI(string mensagem)
    {
        var client = new HttpClient();
        try
        {
            var dados = JsonConvert.SerializeObject(mensagem);
            var request = new HttpRequestMessage(HttpMethod.Post, this.strUrlEnderecoAPI);
            request.Headers.Add("Accept", "application/json");
            request.Content = new StringContent(
                dados.ToString(),
                Encoding.UTF8,
                "application/json"
            );
            var response = client.SendAsync(request).Result;
            var result = response.Content.ReadAsStringAsync().Result;
            return JsonConvert.DeserializeObject<object>(result);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            client.Dispose();
        }
    }

Important that you exchange this.strUrlEnderecoAPI for the address of your cloud API. Important also that in this example I do a post and I get a result, you did not say what HTTP method you need to call, but if you need to do a get just exchange the post for GET.

  • If you have solved your problem please check as solved please, if you have questions you can write them here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.