locked
[WEB API] How to use a Web API with ASP.NET Core ? RRS feed

  • Question

  • User-1370514677 posted

    Hi everyone,

    I'm new to the world of Web APIs, and I'd like to retreive data from a JSON object exposed by this API :

    https://api.coincap.io/v2/assets

    How can I proceed ? (I want to do it in a MVC project)

    I found people using JavaScript, others using Python but not C# ?

    Sunday, March 21, 2021 11:50 AM

All replies

  • User475983607 posted

    valenciano8

    I found people using JavaScript, others using Python but not C# ?

    .NET 5 has the well-known HttpClient library which is part of the fundamentals documentation.  I think you'll be interested in reading the openly published documentation.  

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0

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

    The following is a basic service.

                services.AddHttpClient("assetClient", c =>
                {
                    c.BaseAddress = new Uri("https://api.coincap.io/v2/");
                    c.DefaultRequestHeaders.Add("Accept", "application/json");
                });
    services.AddScoped<IAssetService, AssetService>();

    Impelemtnation.

        public class ApiClientController : Controller
        {
            private readonly ILogger<ApiClientController> _logger;
            private readonly IAssetService _assetService;
            public ApiClientController(
                ILogger<ApiClientController> logger, 
                IAssetService assetService)
            {
                _logger = logger;
                _assetService = assetService;
            }
            public async Task<AssestsVm> GetAssests()
            {
                return await _assetService.GetAssests();
            }

    Model

        public class AssestsVm
        {
            public Assest[] data { get; set; }
            public long timestamp { get; set; }
        }
    
        public class Assest
        {
            public string id { get; set; }
            public string rank { get; set; }
            public string symbol { get; set; }
            public string name { get; set; }
            public string supply { get; set; }
            public string maxSupply { get; set; }
            public string marketCapUsd { get; set; }
            public string volumeUsd24Hr { get; set; }
            public string priceUsd { get; set; }
            public string changePercent24Hr { get; set; }
            public string vwap24Hr { get; set; }
            public string explorer { get; set; }
        }

    Sunday, March 21, 2021 12:47 PM
  • User-1370514677 posted

    Hi @mgebhard,

    Thanks a lot for your answer !

    Yet, in a MVC app, lets assume the following :

    the user won't see the changes applied until he reloads the page right ?

    Because otherwise I was thinking of keeping my MVC app with ASP.NET Core and fetching and modifying the data with a simple JS script instead ?

    Sunday, March 21, 2021 4:40 PM
  • User475983607 posted

    Hi @mgebhard,

    Thanks a lot for your answer !

    Yet, in a MVC app, lets assume the following :

    the user won't see the changes applied until he reloads the page right ?

    Because otherwise I was thinking of keeping my MVC app with ASP.NET Core and fetching and modifying the data with a simple JS script instead ?

    I'm confused...  Your original post indicated you found JS examples but were looking for MVC examples.  I provided a working MVC example using the JSON data you provided.  Now you've changed the URL, data, and requirements?

    Anyway, craft a JavaScript timer and call the API using fetch (or jQuery AJAX).  As you said, you found JS examples.

    https://www.w3schools.com/js/js_timing.asp

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    Sunday, March 21, 2021 6:16 PM
  • User1312693872 posted

    Hi,valenciano8

    How did you fetch the api data? If you got data from action, you can put the data part into a div and then set interval call the action every 10

    seconds :

    <script type="text/javascript">
                $(function () {
                    setInterval(function () { $('#testdiv').load('Home/weather');  }, 10000);               
                })                
            </script>

    Result (a demo for testing, the weather part will reload every 2 seconds):

    This link is about how to call a JSON API and display the result in ASP.NET Core MVC.

    Best Regards,

    Jerry Cai

    Monday, March 22, 2021 8:54 AM
  • User-1370514677 posted

    Hi everyone,

    Well I basically use this piece of code from the MDN :

    fetch("https://api.coincap.io/v2/assets")
        .then(response => response.json())
        .then(data => console.log(data));

    But I think that the client-side approach is not adapted to my issue as many "free" apis will allow a certain number of max requests / month.

    So if I'd do this every 10 seconds my access to the API would pretty be limited.

    I think that I'm going to try the C# server-side approach instead as mgebhard indicated which looks like more suitable.

    I'll keep in you  in touch

    Monday, March 22, 2021 10:30 AM