Getting null using external api with restsharp

Asked

Viewed 83 times

0

I am facing a problem when trying to get an external API that returns Json. Instead of storing the value of json variables in the model is receiving null.

Model:

namespace bitcoin.Models
{
    public class Ticker
    {
        public string high { get; set; }
        public string low { get; set; }
        public string vol { get; set; }
        public string last { get; set; }
        public string buy { get; set; }
        public string sell { get; set; }
        public string date { get; set; }
    }
}

My controller:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using bitcoin.Models;
using RestSharp;

namespace bitcoin.Controllers
{
    [Route("api/Bitcoin")]
    [ApiController]
    public class BitcoinController : ControllerBase
    {
        private readonly BitcoinContext _context;

        public BitcoinController(BitcoinContext context)
        {
            _context = context;
        }

        // GET: api/Conversor
        [HttpGet]
        public IEnumerable<Ticker> GetBit()
        {
            // instantiate the RestClient with the base API url
            var client = new RestClient("https://www.mercadobitcoin.net/api/");

            // specify the resource, e.g. https://api.postcodes.io/postcodes/IP1 3JR
            var getRequest = new RestRequest("BTC/{ticker}");
            getRequest.AddUrlSegment("ticker", "ticker");

            // enviar a solicitação GET e retornar um objeto que contenha a resposta JSON da API
            // var singleBitcoinResponseContainer = client.Execute(getRequest);
            var response = client.Execute<List<Ticker>>(getRequest);

            // get the API's JSON response
            return response.Data;
        }

        // GET: api/Conversor/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Ticker>> GetBitcoinItem(long id)
        {
            var bitcoinItem = await _context.Bitcoin.FindAsync(id);

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

            return bitcoinItem;
        }
    }
}

Json:

{
ticker: {
high: "39388.99998000",
low: "34300.00000000",
vol: "1116.52784675",
last: "37600.00000000",
buy: "37550.00000000",
sell: "37600.00000000",
date: 1563382559
}
}
  • can include in the question an example the json returned by the api?

  • I just entered the Json of the Api

  • note that the attribute "date" is not string, it can be set to int: public int date { get; set; }. Also, unless you’ve put a simplified version of json, it’s not a list, it’s a simple object. If that’s the return, you can get it like this: var response = client.Execute<Ticker>(getRequest);

No answers

Browser other questions tagged

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