Home > Enterprise >  How to save api response in database?
How to save api response in database?

Time:11-10

i want to create app with flutter that call Restful api and when status code is 200 save the response wich is user information in sqlite database. i don't know how call api and save it in database so what can i do? can somebody help me?

CodePudding user response:

It's very simple Your answer has two steps

Step 1: Call api

For this step, you can use the http package implemented for Flutter Examples of http package codes can be seen from this link https://pub.dev/packages/http/example

Step 2: Saving the response in the local database

For this step, you can also use the shared preference package, the sample code of which is available in the link below https://pub.dev/packages/shared_preferences/example

I hope it was useful

CodePudding user response:

To complete this task you need two packages from Pub.dev

  • Ready api get request : will return the data to store into the database

  • HTTP : This package contains a set of high-level functions and classes that make it easy to consume HTTP resources. It's multi-platform, and supports mobile, desktop, and the browser.

  • SQFLITE : SQLite plugin for Flutter. Supports iOS, Android and MacOS.

how to do it ?

you can do it in 4 steps :

  • Create the databse
  • Call the resource from http.get request
  • Format the data as you want to save it using json or string
  • Save the data to the sqfdatabase

 var url =
      Uri.https('www.yourApiLink.com', '/directory/expl/item', {'q': '{http}'});

  // Await the http get response, then decode the json-formatted response.
  var response = await http.get(url);
  if (response.statusCode == 200) {
    var jsonResponse =
        convert.jsonDecode(response.body) as Map<String, dynamic>;
    var itemCount = jsonResponse['totalItems'];
    String response_str = jsonResponse.toString();
    
// Insert some records in a transaction
await database.transaction((txn) async {
  int id1 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
  print('inserted1: $id1');
  int id2 = await txn.rawInsert(
      'INSERT INTO Test(name, value, num) VALUES(?, ?)',
      ['response', $response_str]);
  
});

  } else {
    print('Request failed with status: ${response.statusCode}.');
  }

You need first to do this for sqflite

// Get a location using getDatabasesPath
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');


// open the database
Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  // When creating the db, create the table
  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});

Note : This is not a copy paste answer you have to adapt it to your problem

  • Related