HomeInterview QuestionsWrite REST API code to call an external API and st…

Write REST API code to call an external API and store the retrieved data.

🟡 Medium Coding Junior level
1Times asked
Jun 2026Last seen
Jun 2026First seen

💡 Model Answer

Here’s a simple Flask example that exposes a /fetch endpoint. When called, it requests data from an external API, parses the JSON response, and stores it in a SQLite database.

python
from flask import Flask, jsonify
import requests, sqlite3

app = Flask(__name__)

# Create a simple table
conn = sqlite3.connect('data.db', check_same_thread=False)
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS items(id INTEGER PRIMARY KEY, name TEXT, value REAL)')
conn.commit()

@app.route('/fetch', methods=['GET'])
def fetch_and_store():
    # Call external API
    resp = requests.get('https://api.example.com/items')
    resp.raise_for_status()
    items = resp.json()  # assume list of dicts with keys id, name, value

    # Store into DB
    with conn:
        for item in items:
            c.execute('INSERT OR REPLACE INTO items(id, name, value) VALUES(?,?,?)',
                      (item['id'], item['name'], item['value']))
    return jsonify({'status': 'success', 'count': len(items)})

if __name__ == '__main__':
    app.run(debug=True)

Explanation

  • The endpoint /fetch is a simple GET that triggers the external call.
  • requests.get performs the HTTP call; error handling is done via raise_for_status.
  • The JSON payload is iterated and inserted into SQLite using INSERT OR REPLACE to avoid duplicates.
  • Complexity is O(n) where n is the number of items returned; database operations are batched by the context manager.

For production you’d replace SQLite with a proper RDBMS or NoSQL store, add authentication, pagination, and asynchronous handling (e.g., using aiohttp and asyncio).

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500