Mıktad Tahir Durak
Mıktad Tahir Durak

Reputation: 2864

Flutter 500 error on API when trying to make authenticated requests

I'm trying to make authenticated requests, but I get 500 errors. when I change my token, I get 401 error which is not authenticated meaning.

Here is my code:

import 'dart:convert';
import 'dart:io';
import 'myapp/models/apis/stocks.dart';
import 'package:http/http.dart' as http;

class StocksService {
  final String url = "https://api.collectapi.com/economy/hisseSenedi";

  Future<StocksModel?> fetchStocks() async {
    var res = await http.get(
      Uri.parse(url),      
      headers: {
        HttpHeaders.authorizationHeader:
            "apikey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
      },
    );
    if (res.statusCode == 200) {
      var jsonBody = StocksModel.fromJson(jsonDecode(res.body));
      return jsonBody;
    } else {
      print("İstek başarısız oldu => ${res.statusCode}");
    }
  }
}

Is there anything wrong in code?

Upvotes: 0

Views: 361

Answers (1)

Your header is wrong. I have a simple code for this:

import 'package:wnetworking/wnetworking.dart';


class CollectApi {
  final _url = 'https://api.collectapi.com/economy';
  final _token = '1111111111111111111111111111111';
  /* ---------------------------------------------------------------------------- */
  CollectApi();
  /* ---------------------------------------------------------------------------- */
  Future<void> hisseSenedi() async {
    var result = await HttpReqService.get<JMap>(
      '$_url/hisseSenedi',
      auth: AuthType.apiKey,
      authData: MapEntry('Authorization', 'apikey $_token'),
    );

    print(result.toString().substring(0,100));
  }
}

void main(List<String> args) async {
  await CollectApi().hisseSenedi();
  print('Job done!');
}

Output:

{success: true, result: [{rate: 3.08, lastprice: 19.39, lastpricestr: 19,39, hacim: , hacimstr: ₺5.5
Job done!

wnetworking package is based on http.

Upvotes: 2

Related Questions