Search code examples
apiflutterhttpgethttp-status-code-404

Flutter - not able to fetch data from api via http.get


I'm trying to fetch data from Unsplash API to my Flutter app but I'm still getting error 404. To connect with API I'm using dart:http package v.0.13 . I tried to use the same Uri on Postman and I'm getting status code 200 so URL is fine (https://api.unsplash.com/photos/random/?client_id=API_KEY). Please check my code.

Future<void> getRandomImage() async {
var res = await http.get(Uri.https('api.unsplash.com',
    '/photos/random/?client_id=API_KEY'));
if (res.statusCode == 200) {
  var decodedData = jsonDecode(res.body);
  print(decodedData);
} else {
  print(res.statusCode);
  throw 'Problem with the get request';
}}

Solution

  • NetService:

    class NetService {
      static Future<T?> getJson<T>(String url, {int okCode = 200}) {
        return http.get(Uri.parse(url))
          .then((response) {
            if (response.statusCode == okCode) {
              return jsonDecode(response.body) as T;
            }
            PrintService.showDataNotOK(response);
            return null;
          })
          .catchError((err) => PrintService.showError(err));
      }
    }
    

    Main:

    import 'dart:async';
    
    import 'package:_samples2/networking.dart';
    
    class Unsplash {
      static const _apiKey = '11111111111111111111111111111';
      static const _url = 'https://api.unsplash.com/photos/random/?client_id=$_apiKey';
    
      static FutureOr<void> fetchRandomImage() async {
        print('Start fetching...\n');
        await NetService.getJson<Map<String, dynamic>>(_url)
          .then((response) => print(response))
          .whenComplete(() => print('\nFetching done!'));
      }
    }
    
    void main(List<String> args) async {
      await Unsplash.fetchRandomImage();
      print('Done!');
    }
    

    Result:

    Start fetching...
    
    {id: 6qUn2lQF9A4, created_at: 2021-03-06T08:38:48-05:00, updated_at: 2021-03-12T01:39:06-05:00, promoted_at: 2021-03-07T04:56:18-05:00, width: 6000, height: 4000, color: #735959, blur_hash: LJEVHCRk0LWXM_oJt7ozNGWBs:of, description: null, alt_description: woman with blonde hair holding a pen, urls: {raw: https://images.unsplash.com/photo-1615037486765-e96acbe87231?ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1, full: https://images.unsplash.com/photo-1615037486765-e96acbe87231?crop=entropy&cs=srgb&fm=jpg&ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1&q=85, regular: https://images.unsplash.com/photo-1615037486765-e96acbe87231?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1&q=80&w=1080, small: https://images.unsplash.com/photo-1615037486765-e96acbe87231?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1&q=80&w=400, thumb: https://images.unsplash.com/photo-1615037486765-e96acbe87231?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1&q=80&w=200}, links: {self: https://api.unsplash.com/photos/6qUn2lQF9A4, html: https://unsplash.com/photos/6qUn2lQF9A4, download: https://unsplash.com/photos/6qUn2lQF9A4/download, download_location: https://api.unsplash.com/photos/6qUn2lQF9A4/download?ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ}, categories: [], likes: 13, liked_by_user: false, current_user_collections: [], sponsorship: null, user: {id: PZ7vHHbEDBs, updated_at: 2021-03-12T05:45:35-05:00, username: victoriapriessnitz, name: Victoria Priessnitz, first_name: Victoria, last_name: Priessnitz, twitter_username: null, portfolio_url: https://www.instagram.com/victoriapriessnitz_photo/, bio: www.priessnitzstudio.cz
    https://www.instagram.com/priessnitzstudio/
    , location: Czech Republic, links: {self: https://api.unsplash.com/users/victoriapriessnitz, html: https://unsplash.com/@victoriapriessnitz, photos: https://api.unsplash.com/users/victoriapriessnitz/photos, likes: https://api.unsplash.com/users/victoriapriessnitz/likes, portfolio: https://api.unsplash.com/users/victoriapriessnitz/portfolio, following: https://api.unsplash.com/users/victoriapriessnitz/following, followers: https://api.unsplash.com/users/victoriapriessnitz/followers}, profile_image: {small: https://images.unsplash.com/profile-1588431995209-edb1b4743462image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32, medium: https://images.unsplash.com/profile-1588431995209-edb1b4743462image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64, large: https://images.unsplash.com/profile-1588431995209-edb1b4743462image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128}, instagram_username:  victoriapriessnitz_photography, total_collections: 0, total_likes: 4, total_photos: 266, accepted_tos: true, for_hire: false}, exif: {make: null, model: null, exposure_time: null, aperture: null, focal_length: null, iso: null}, location: {title: null, name: null, city: null, country: null, position: {latitude: null, longitude: null}}, views: 91851, downloads: 939}
    
    Fetching done!
    Done!