Home > OS >  Getting data from ASP.NET Core API
Getting data from ASP.NET Core API

Time:11-27

I am working on Market and Financial News app.I took the API from https://www.marketaux.com/. I am trying to display the news from the site into my home page. I have created a model file and controller in ASP.NET Core web app file. In controller file, I get an error in response.data part as its showing response doesn't have data object whereas when I print the output of response.Content, it has data object. Can you tell me how to solve this and get access to the data from the API so that I can display it on my Home page?

Controller class:

using System.Runtime.CompilerServices;
using Azure.Core;
using MarketNews.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI;
using Newtonsoft.Json;
using RestSharp;

namespace MarketNews.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NewsController : ControllerBase
    {
        [HttpGet]
        public News[] GetNews() 
        {
            List<News> news = new List<News>();
            RestClient client = new RestClient("https://api.marketaux.com/v1/news/all");
            // client.Timeout = -1;

            RestRequest request = new RestRequest("News",Method.Get);
            request.AddQueryParameter("api_token", "qIWtsblpK93oeo23o87egUGBoVmVaqkl4fdHRTEc");
            request.AddQueryParameter("symbols", "aapl,amzn");
            request.AddQueryParameter("limit", "50");

            RestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

            if (response != null)
            {
                foreach (var article in response.data)
                {
                    news.Add(new News
                    {
                        Title = article.title,
                        Description = article.description,
                        Url = article.url,
                        Url_Image = article.image_url,
                        Published_At = article.published_at
                    });
                }
            }

            return news.ToArray();
        }
    }
}

Model class

namespace MarketNews.Models
{
    public class News
    {
        public string Title;
        public string Description;
        public string Url;
        public string Url_Image;
        public DateTime Published_At;
    }
}

I wanted to get data from the API and display it on my Home Page. I used RestClient and RestRequest to get response and then from response. I got the output when response.Content printed to console, it is working and it gave me a json file as output. In foreach loop when I tried to set the response data to the model data I created, it's showing response.data doesn't exist.

I want to know what is wrong here or is there any other method to get the data from the API?

Api: Website link

CodePudding user response:

From RestSharp documentation, the Execute() method does support for a generic type.

Execute<T>(IRestRequest request)

Note that, this method is deprecated. You shall look for the method below:

ExecuteAsync<T>(IRestRequest request, CancellationToken cancellationToken)

and revamp your API action to support asynchronous operation.

From the response data shared in the link, you need a Root object which contains the data property with the List<New> type.

  1. Define the data model class for the response.
using System.Text.Json;

public class Root
{
    [JsonPropertyName("data")]
    public List<News> Data { get; set; }
}
public class News
{
    [JsonPropertyName("title")]
    public string Title { get; set; }
    
    [JsonPropertyName("description")]
    public string Description { get; set; }

    [JsonPropertyName("url")]
    public string Url { get; set; }

    [JsonPropertyName("image_url")]
    public string Url_Image { get; set; }

    [JsonPropertyName("published_at")]
    public DateTime Published_At { get; set; }
}
  1. For the caller, specify the generic type as Root. Next extract the data property from the response with response.Data.Data.
RestResponse<Root> response = client.Execute<Root>(request);

// asynchronous way
// RestResponse<Root> response = await client.ExecuteAsync<Root>(request);

if (response != null)
    news = response.Data.Data;
  • Related