Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


System Design – Interview Questions

  1. What is the purpose of software system design?
    Software system design aims to transform user requirements into a well-organized and structured solution by defining system architecture, modules, interfaces, and other components.
  2. Explain the difference between monolithic and microservices architectures.
    Monolithic architecture is a single, tightly integrated application, while microservices use small, independent services communicating through APIs. Example: Monolithic – A traditional web application; Microservices – Netflix architecture.
  3. How do you decide between a relational database and a NoSQL database for a specific application?
    Use a relational database when data consistency and strong ACID properties are crucial. Use NoSQL databases when scalability and flexible schema are required. Example: Relational – Banking application; NoSQL – Real-time analytics platform.
  4. What is the role of load balancing in a distributed system?
    Load balancing distributes incoming network traffic across multiple servers to ensure optimal resource utilization and prevent overload on any single server. Example: Nginx for distributing web traffic across application servers.
  5. How can you ensure data security in a distributed system?
    Implement encryption, authentication, and authorization mechanisms, use secure communication protocols (e.g., HTTPS), and regularly update security patches. Example: Using SSL/TLS for securing data transmission in a distributed e-commerce system.
  6. Explain the concept of caching and its significance in software system design.
    Caching stores frequently accessed data in a temporary storage, reducing the need to fetch the same data repeatedly from the original source, which improves system performance. Example: Caching frequently accessed database query results in a web application.
  7. Describe the “Database Sharding” technique and when it’s useful.
    Database sharding involves horizontally partitioning data across multiple databases to handle large datasets and improve scalability. It’s useful when a single database becomes a performance bottleneck. Example: Sharding user data based on geographical regions in a global social media platform.
  8. What are design patterns, and how do they benefit software system design?
    Design patterns are reusable solutions to common software design problems. They enhance system maintainability, scalability, and code quality. Example: Singleton pattern to ensure only one instance of a class exists.
  9. Explain the role of an API gateway in a microservices architecture.
    An API gateway acts as a single entry point for client requests, routing them to appropriate microservices. It handles tasks like authentication, rate limiting, and request/response transformations. Example: Netflix Zuul as an API gateway for their microservices.
  10. What is event-driven architecture, and why is it popular in modern systems?
    Event-driven architecture enables communication between components through events, facilitating loose coupling and scalability. It is popular because it enables real-time processing, responsiveness, and adaptability. Example: Using Apache Kafka for real-time data streaming and processing in a financial trading platform.
  11. How can you ensure high availability in a distributed system?
    Ensure redundancy through replication, utilize load balancing, implement failover mechanisms, and design for fault tolerance. Example: Using a distributed database with replication across multiple data centers for high availability.
  12. Discuss the pros and cons of a RESTful API compared to a GraphQL API.
    RESTful API pros: Simplicity, standardized, statelessness. Cons: Over-fetching, under-fetching. GraphQL pros: Flexibility, efficient data retrieval. Cons: Complexity. Example: RESTful API for a basic CRUD application; GraphQL API for a data-intensive application with complex data needs.
  13. What are the key considerations when designing a scalable system?
    Vertical and horizontal scaling, load balancing, caching, statelessness, and sharding. Example: Designing a scalable e-commerce platform that can handle an increasing number of users and transactions.
  14. Explain the role of Docker in software system design and deployment.
    Docker facilitates containerization, allowing applications to run consistently across different environments and simplifying deployment and scaling processes. Example: Dockerizing a web application to ensure it runs the same way in development, testing, and production environments.
  15. How can you optimize the performance of a database query?
    Optimize database indexes, minimize database joins, use database caching, and denormalize data when necessary. Example: Adding indexes to frequently queried columns in a relational database.
  16. Describe the principles of the SOLID design principles.
    SOLID stands for Single Responsibility Principle, Open/Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle. These principles enhance code maintainability, extensibility, and readability. Example: Following the Single Responsibility Principle by separating UI logic from business logic in an application.
  17. How can you ensure data consistency in a distributed system?
    Use distributed transactions or implement eventual consistency through mechanisms like CRDTs (Conflict-Free Replicated Data Types). Example: Implementing distributed transactions for multi-region writes in a banking application.
  18. Explain the role of an Application Load Balancer (ALB) in cloud-based systems
    An ALB distributes incoming application traffic across multiple targets (e.g., EC2 instances) within an Auto Scaling group, ensuring high availability and fault tolerance. Example: Using AWS Application Load Balancer to distribute incoming HTTP traffic across EC2 instances hosting a web application.
  19. How do you handle long-running tasks in a web application?
    Use background processing or task queues to handle long-running tasks asynchronously, freeing up resources for other requests. Example: Using Celery with RabbitMQ as a task queue to process image uploads in a social media application.
  20. Discuss the differences between synchronous and asynchronous communication in distributed systems.
    Synchronous communication waits for a response before proceeding, while asynchronous communication continues without waiting for an immediate response. Asynchronous communication is often preferred for scalability and responsiveness. Example: Synchronous – Traditional HTTP request-response; Asynchronous – Messaging systems like RabbitMQ or Apache Kafka.
July 19, 2023

Flask – Interview Questions

  1. What is Flask?
    Flask is a micro web framework in Python that is used to build web applications. It is simple, lightweight, and follows the WSGI (Web Server Gateway Interface) standard.
    Flask is a lightweight framework, which makes it easy to get started with. It is also very flexible, which allows you to customize your application to your specific needs.
  2. What are the disadvantages of using Flask?
    Flask is a microframework, which means that it does not come with a lot of features out of the box. You may need to install additional packages to add features like database support or authentication.
  3. What is the difference between Flask and Django?
    Flask and Django are both web frameworks for Python. However, they have different philosophies. Flask is a microframework, while Django is a full-featured framework. This means that Flask is more lightweight and flexible, while Django is more powerful and has more features.
  4. How do you install Flask?
    You can install Flask using pip:
  5. Explain how to create a basic Flask application.

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        return "Hello, Flask!"
    

     

  6. What are some of the popular Flask extensions?
    Some of the popular Flask extensions include:
    * Flask-SQLAlchemy: This extension provides database support for Flask.
    * Flask-Login: This extension provides authentication support for Flask.
    * Flask-WTF: This extension provides form validation support for Flask.
  7. What is route in Flask?
    A route in Flask is a URL pattern associated with a view function. When a user requests a specific URL, Flask maps the URL to the corresponding view function defined in the application.
    To define routes in Flask, you can use the @app.route() decorator. The @app.route() decorator takes a URL as the argument and a function as the value. The function that you pass to the @app.route() decorator will be called when the URL is requested.
  8. How do you run a Flask application?

    @app.route('/user/<username>')
    def show_user(username):
        return f"Hello, {username}!"
    
  9. How do you perform URL redirect in Flask?
    You can use the redirect() function to redirect to another URL.

    from flask import redirect
    
    @app.route('/old-url')
    def old_url():
        return redirect('/new-url')
    

     

  10. How do you handle errors in Flask?
    To handle errors in Flask, you can use the @app.errorhandler() decorator. The @app.errorhandler() decorator takes an error code as the argument and a function as the value. The function that you pass to the @app.errorhandler() decorator will be called when the error code is encountered.In Flask, you can handle errors using error handlers and exception handling. Flask provides ways to customize error pages for different HTTP status codes and also allows you to handle exceptions that might occur during the execution of your application. Let’s look at both methods:Error Handlers: Flask allows you to create custom error handlers for specific HTTP status codes. You can use the @app.errorhandler decorator to define error handlers for various status codes.

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return "Hello, Flask!"
    
    # Custom error handler for 404 Not Found
    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html'), 404
    
    # Custom error handler for 500 Internal Server Error
    @app.errorhandler(500)
    def internal_server_error(error):
        return "Internal Server Error", 500
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    Exception handling in Flask allows you to catch and handle exceptions that occur during the execution of your application. You can use the try, except, and finally blocks to handle exceptions and respond accordingly.

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return "Hello, Flask!"
    
    @app.route('/divide/<int:num>')
    def divide_by_zero(num):
        try:
            result = 10 / num
            return f"The result is: {result}"
        except ZeroDivisionError:
            return "Error: Cannot divide by zero."
        except Exception as e:
            return f"An error occurred: {str(e)}"
    
    if __name__ == '__main__':
        app.run(debug=True)
    

     

  11. What is Flask-WTF and how is it used? Flask-WTF is an extension that provides integration with WTForms, allowing you to create and handle forms in Flask applications.
    from flask_wtf import FlaskForm
    from wtforms import StringField, SubmitField
    
    class MyForm(FlaskForm):
        name = StringField('Name')
        submit = SubmitField('Submit')
    

     

  12. What are Flask Blueprints? Flask Blueprints are used to organize a Flask application into smaller, reusable components. They allow you to register views, templates, and static files for a specific feature or module.
  13. Explain the use of Flask-SQLAlchemy. Flask-SQLAlchemy is an extension that integrates SQLAlchemy with Flask, providing an easy way to work with databases in Flask applications.
  14. How can you connect a Flask application to a database using Flask-SQLAlchemy?

    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
    db = SQLAlchemy(app)
    

     

     

  15. How do you define a model in Flask-SQLAlchemy?

    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(80), unique=True, nullable=False)
        email = db.Column(db.String(120), unique=True, nullable=False)
    
        def __repr__(self):
            return f'<User {self.username}>'
    

     

  16. Explain Flask-Migrate and its purpose. Flask-Migrate is an extension that allows you to manage database migrations in Flask-SQLAlchemy applications. It helps to keep the database schema in sync with the application models.
  17. What is Flask-RESTful used for? Flask-RESTful is an extension that simplifies the process of building RESTful APIs in Flask. It provides features for defining resources, request parsing, and handling HTTP methods.
  18. Explain how to create a simple RESTful API using Flask-RESTful.

    from flask import Flask
    from flask_restful import Resource, Api
    
    app = Flask(__name__)
    api = Api(app)
    
    class HelloWorld(Resource):
        def get(self):
            return {'message': 'Hello, World!'}
    
    api.add_resource(HelloWorld, '/')
    
    if __name__ == '__main__':
        app.run(debug=True)
    

     

     

  19. What is the use of Flask-JWT? Flask-JWT (JSON Web Tokens) is an extension that provides a secure way to authenticate users and generate tokens for access control in Flask applications.
  20. Explain how to secure a Flask API using Flask-JWT.

    from flask_jwt import JWT, jwt_required, current_identity
    from werkzeug.security import safe_str_cmp
    
    # Sample user class
    class User:
        def __init__(self, id, username, password):
            self.id = id
            self.username = username
            self.password = password
    
    # Dummy user data
    users = [
        User(1, 'user1', 'password1'),
        User(2, 'user2', 'password2')
    ]
    
    # JWT authentication functions
    def authenticate(username, password):
        user = next((user for user in users if user.username == username), None)
        if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
            return user
    
    def identity(payload):
        user_id = payload['identity']
        return next((user for user in users if user.id == user_id), None)
    
    app.config['SECRET_KEY'] = 'super-secret-key'
    jwt = JWT(app, authenticate, identity)
    
    @app.route('/protected')
    @jwt_required()
    def protected():
        return f'Hello, {current_identity.username}!'
    

     

     

  21. What is Flask-Caching and how is it used? Flask-Caching is an extension that adds caching support to Flask applications, improving the performance of repetitive tasks.
  22. Explain how to implement caching in Flask using Flask-Caching.

    from flask_caching import Cache
    
    app = Flask(__name__)
    app.config['CACHE_TYPE'] = 'simple'
    cache = Cache(app)
    
    @app.route('/slow')
    @cache.cached(timeout=60)
    def slow_function():
        # Expensive calculation or operation
        return "Slow response"
    
    if __name__ == '__main__':
        app.run(debug=True)
    

     

     

  23. Explain the use of Flask-SocketIO. Flask-SocketIO is an extension that provides WebSocket support to Flask applications, allowing real-time bidirectional communication between the server and clients.
  24. Explain how to use Flask-SocketIO to implement real-time communication.

    from flask import Flask, render_template
    from flask_socketio import SocketIO
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret_key'
    socketio = SocketIO(app)
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @socketio.on('message')
    def handle_message(message):
        print('Received message: ', message)
        socketio.send('Message received: ' + message)
    
    if __name__ == '__main__':
        socketio.run(app, debug=True)
    

     

     

  25. How do you deploy a Flask application?
    To deploy a Flask application, you can use a variety of methods. One common method is to use a web server like Gunicorn or uWSGI. You can also deploy a Flask application to a cloud platform like Heroku or AWS.
  26. What is the MVC pattern? The MVC (Model-View-Controller) pattern is a software design pattern used to organize the structure of web applications. It separates the application into three interconnected components:Model: Represents the data and business logic of the application.
    View: Handles the presentation and user interface.
    Controller: Manages the user input, processes requests, and updates the model and view accordingly.
    In Flask, the View and Controller components are often combined into views and routed using decorators.
  27.  
  28. What are the different types of HTTP requests? The main types of HTTP requests are:
    • GET: Used to request data from a specified resource.
    • POST: Used to submit data to be processed to a specified resource.
    • PUT: Used to update a resource or create one if it doesn’t exist.
    • DELETE: Used to delete a specified resource.
    • PATCH: Used to partially update a resource.
    • HEAD: Similar to GET, but retrieves only the headers of a resource.

    In Flask, you can handle these HTTP requests using different route decorators (@app.route) to specify the URL patterns for each type.

  29. What is the difference between a GET and a POST request?
      
    The main differences between a GET and a POST request are:

    • GET: Requests data from a specified resource, and the data is appended to the URL as query parameters. GET requests are less secure as the data is visible in the URL, making it unsuitable for sensitive information.
    • POST: Submits data to be processed to a specified resource, and the data is sent in the request body. POST requests are more secure and can handle larger data payloads compared to GET requests.

    In Flask, you can handle both GET and POST requests using the route decorators (@app.route) and request methods in view functions.

  30. How do you use the Flask debugger?
    The Flask debugger is a built-in feature that helps in debugging Flask applications. To enable the debugger, you can set the debug parameter to True when creating the Flask application:

    from flask import Flask
    
    app = Flask(__name__)
    app.debug = True
    

     

  31. How do you use the Flask test client? The Flask test client is used to simulate HTTP requests to the application during testing. It allows you to test views and routes without making actual requests to the server. You can use the test client as follows:
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return "Hello, Flask!"
    
    with app.test_client() as client:
        response = client.get('/')
        print(response.data)  # Output: b'Hello, Flask!'
    

     

  32.  
July 19, 2023

Python Advanced – Interview Questions

  1. What is Python?
    Python is a high-level, interpreted, and dynamically-typed programming language known for its simplicity and readability.
  2. What are the key features of Python?
    Key features of Python include readability, simplicity, extensibility, object-oriented programming, and a large standard library.
  3. What is PEP 8?
    PEP 8 is the official style guide for Python, providing guidelines on how to format Python code for improved readability and consistency.
  4. How do you comment in Python?
    You can use the ‘#’ symbol to add single-line comments and triple quotes (”’ ”’) for multi-line comments.

    # This is a single-line comment
    
    '''
    This is a multi-line comment
    Line 1
    Line 2
    '''
    
  5. What is the difference between lists and tuples? Lists are mutable, while tuples are immutable. Lists use square brackets ([ ]) and allow modifications, while tuples use parentheses (()) and cannot be changed after creation.
    my_list = [1, 2, 3]
    my_tuple = (4, 5, 6)
    
    my_list[0] = 10  # Valid, modifies the list
    # my_tuple[0] = 10  # Invalid, will raise an error
    

     

  6. What are Python decorators?
    Decorators are a powerful feature in Python that allow you to modify the behavior of functions or methods without changing their code directly.

    def my_decorator(func):
        def wrapper():
            print("Something is happening before the function is called.")
            func()
            print("Something is happening after the function is called.")
        return wrapper
    
    @my_decorator
    def say_hello():
        print("Hello!")
    
    say_hello()
    

    A decorator is a function that takes another function as its input and returns a new function. The new function is a wrapper around the original function.

    def debug(func):
        def wrapper(*args, **kwargs):
            print('Calling {}'.format(func.__name__))
            return func(*args, **kwargs)
        return wrapper
    
    @debug
    def factorial(n):
        if n == 0:
            return 1
        else:
            return n * factorial(n - 1)
    
    print(factorial(5))
    

     

  7. Explain the difference between ‘is’ and ‘==’ in Python. ‘is’ checks if two variables refer to the same object in memory, while ‘==’ checks if the values of the two variables are equal.
    x = [1, 2, 3]
    y = x
    
    print(x is y)  # True
    print(x == y)  # True
    
    z = [1, 2, 3]
    print(x is z)  # False
    print(x == z)  # True
    
  8. What are lambda functions? Lambda functions are anonymous functions defined using the lambda keyword. They are typically used for short, simple tasks.
    add = lambda x, y: x + y
    print(add(2, 3))  # Output: 5
    
  9. Explain list comprehension.
    List comprehension is a concise way to create lists in Python. It allows you to create a new list by applying an expression to each item in an existing iterable.

    squares = [x ** 2 for x in range(1, 6)]
    print(squares)  # Output: [1, 4, 9, 16, 25]
    

    A comprehension is a concise way to create a list, set, or dictionary. Comprehensions are often used to filter or transform a sequence of values.

    even_numbers = [i for i in range(10) if i % 2 == 0]
    squares = {i ** 2 for i in range(10)}
    names_and_ages = {name: age for name, age in zip(['John', 'Jane', 'Mary'], [30, 25, 40])}
    

     

  10. How can you handle exceptions in Python? Exception handling in Python is done using try, except, else, and finally blocks. The try block contains the code that may raise an exception, and the except block handles the exception if it occurs.
    try:
        num = int(input("Enter a number: "))
        result = 10 / num
    except ZeroDivisionError:
        print("Error: Cannot divide by zero.")
    except ValueError:
        print("Error: Invalid input. Please enter a number.")
    else:
        print("Result:", result)
    finally:
        print("Execution completed.")
    
  11. Explain the concept of generators in Python.
    Generators are functions that use the yield keyword to return an iterator, allowing you to iterate over a sequence of values without generating the entire sequence at once.

    def countdown(n):
        while n > 0:
            yield n
            n -= 1
    
    for i in countdown(5):
        print(i)
    
    5
    4
    3
    2
    1
    

    A generator is a function that can be used to iterate over a sequence of values. Generators are often used to create iterators, which are objects that can be used to iterate over a sequence of values.

    def fibonacci(n):
        a, b = 0, 1
        for i in range(n):
            yield a
            a, b = b, a + b
    
    for i in fibonacci(10):
        print(i)
    
  12. What is the difference between __str__ and __repr__?
    __str__ is used to provide a user-friendly string representation of an object, while __repr__ is used to provide a developer-friendly string representation, often used for debugging.

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def __str__(self):
            return f"{self.name}, {self.age} years old."
    
        def __repr__(self):
            return f"Person('{self.name}', {self.age})"
    
    person = Person("Alice", 30)
    print(str(person))  # Output: Alice, 30 years old.
    print(repr(person)) # Output: Person('Alice', 30)
    
  13. Explain the Global Interpreter Lock (GIL) in Python.
    The GIL is a mutex used in CPython (the reference implementation of Python) to ensure that only one thread executes Python bytecode at a time. This can impact multi-threaded performance in CPU-bound applications.
  14. What is the use of the ‘pass’ statement in Python?
    The ‘pass’ statement is a no-op and is used as a placeholder when a statement is syntactically required but you don’t want to execute any code.

    if x < 0:
        pass  # Placeholder for handling negative numbers
    else:
        print("Positive number")
    
  15. What is the difference between a class and an object?
    A class is a blueprint for creating objects. An object is an instance of a class.

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def say_hello(self):
            print('Hello, my name is {}'.format(self.name))
    
    person = Person('John Doe', 30)
    person.say_hello()
    

     

  16. What are the different types of inheritance in Python?
    There are three types of inheritance in Python:

    • Single inheritance: A class inherits from a single parent class.
    • Multilevel inheritance: A class inherits from multiple parent classes.
    • Hierarchical inheritance: A class inherits from a parent class, which inherits from another parent class, and so on.
      class Animal:
          def __init__(self, name):
              self.name = name
      
          def make_sound(self):
              print('I am an animal!')
      
      class Dog(Animal):
          def __init__(self, name, breed):
              super().__init__(name)
              self.breed = breed
      
          def bark(self):
              print('Woof!')
      
      class Cat(Animal):
          def __init__(self, name, fur_color):
              super().__init__(name)
              self.fur_color = fur_color
      
          def meow(self):
              print('Meow!')
      
      dog = Dog('Sparky', 'Golden Retriever')
      dog.bark()
      cat = Cat('Mittens', 'Black')
      cat.meow()
      
  17. What is the purpose of the ‘with’ statement in Python? The ‘with’ statement is used to ensure that certain operations are performed safely and automatically, such as file handling or acquiring/releasing locks.
    with open("example.txt", "r") as file:
        data = file.read()
    # The file is automatically closed after exiting the 'with' block
    
  18. How can you copy an object in Python?
    You can copy objects using the copy module or using the slice operator.

    import copy
    
    # Shallow copy using copy module
    original_list = [1, 2, 3]
    copied_list = copy.copy(original_list)
    
    # Deep copy using copy module
    original_list = [1, [2, 3], 4]
    copied_list = copy.deepcopy(original_list)
    
    # Shallow copy using slice operator
    original_list = [1, 2, 3]
    copied_list = original_list[:]
    
  19. What are the main differences between Python 2 and Python 3?
    Python 3 introduced several backward-incompatible changes like print function, integer division, and Unicode support. Python 2 reached its end of life on January 1, 2020.
  20. Explain the concept of multiple inheritance in Python.
    Multiple inheritance allows a class to inherit attributes and methods from more than one base class. In Python, a class can have multiple base classes separated by commas in the class declaration.

    class A:
        def method_a(self):
            print("Method A")
    
    class B:
        def method_b(self):
            print("Method B")
    
    class C(A, B):
        pass
    
    obj = C()
    obj.method_a()  # Output: Method A
    obj.method_b()  # Output: Method B
    
  21. How can you handle file I/O in Python?
    You can use the built-in functions open() to open a file and perform operations like reading, writing, or appending data.

    # Writing to a file
    with open("data.txt", "w") as file:
        file.write("Hello, World!")
    
    # Reading from a file
    with open("data.txt", "r") as file:
        content = file.read()
        print(content)  # Output: Hello, World!
    
  22. Explain the use of virtual environments in Python.
    Virtual environments allow you to create isolated Python environments to manage dependencies and package versions for different projects.
  23. What is the difference between a mock object and a stub object?
    Mock objects and stub objects are both used in unit testing to simulate the behavior of real objects. However, there are some key differences between the two.A mock object is a fake object that is created to test the behavior of a real object. Mock objects can be used to verify that a real object is called with the correct arguments and that it returns the correct values.A stub object is a fake object that is created to provide canned responses to requests. Stub objects can be used to simulate the behavior of a real object without having to actually create the real object.

    def factorial(n):
        if n == 0:
            return 1
        else:
            return n * factorial(n - 1)
    
    def test_factorial():
        # Create a mock object that simulates the behavior of a real function.
        mock_factorial = mock.Mock()
        mock_factorial.return_value = 120
    
        # Use the mock object to test the factorial function.
        assert factorial(5) == mock_factorial.call_count
    
        # Create a stub object that provides canned responses to requests.
        stub_factorial = stub.Stub()
        stub_factorial.return_value = 120
    
        # Use the stub object to test the factorial function.
        assert factorial(5) == stub_factorial.return_value
    
  24. What is the difference between unittest and pytest?
    Here are some of the key differences between unittest and pytest:

    • Syntax: unittest uses a more verbose syntax than pytest. For example, unittest requires you to explicitly define a class for each test case, while pytest allows you to define test cases directly in functions.
    • Fixtures: unittest does not have a built-in fixture system, while pytest does. Fixtures are reusable bits of code that can be used to set up or tear down your tests.
    • Assertions: unittest and pytest both have assertion libraries, but pytest‘s assertions are more concise and expressive. For example, unittest requires you to use the assertEqual() method to compare two values, while pytest allows you to use the more expressive assert statement.
    • Plugins: pytest has a plugin system that allows you to extend its functionality. There are many plugins available for pytest, including plugins for generating test reports, collecting code coverage data, and running tests in parallel.

    In general, pytest is a more modern and expressive testing framework than unittest. However, unittest is still a widely used testing framework, and it may be a better choice for some projects.

  25. What is the difference between a continuous integration (CI) server and a continuous delivery (CD) server?

    • Continuous integration (CI) is a practice of merging code changes into a shared repository on a regular basis. This helps to identify and fix bugs early in the development process.
    • Continuous delivery (CD) is a practice of automatically deploying code changes to a production environment after they have been merged into a shared repository. This helps to ensure that code changes are always available to users.

    A CI server is a tool that automates the process of continuous integration. A CD server is a tool that automates the process of continuous delivery.

    Here is an example of how a CI server and a CD server can be used together:

    1. A developer makes a change to a code file.
    2. The developer commits the change to a shared repository.
    3. The CI server automatically runs tests on the code change.
    4. If the tests pass, the CI server automatically deploys the code change to a staging environment.
    5. The developer tests the code change in the staging environment.
    6. If the code change is working correctly, the CD server automatically deploys the code change to a production environment.
  26. What is the difference between a microservice architecture and a monolithic architecture?

    • Microservice architecture is a software architecture style that structures an application as a collection of loosely coupled services. Each service is self-contained and performs a specific task.
    • Monolithic architecture is a software architecture style that structures an application as a single unit. All of the code for the application is contained in a single unit.

    Microservice architecture is more scalable and flexible than monolithic architecture. However, it can be more complex to develop and maintain.

    Here is an example of how a microservice architecture and a monolithic architecture can be used:

    • Microservice architecture: An e-commerce application might be divided into microservices for the product catalog, the shopping cart, the checkout process, and the shipping and billing system.
    • Monolithic architecture: An e-commerce application might be implemented as a single unit with all of the code for the product catalog, the shopping cart, the checkout process, and the shipping and billing system in a single codebase.
  27. What is the difference between a RESTful API and a SOAP API?

    • RESTful API is an API that uses the Representational State Transfer (REST) architectural style. REST APIs are based on the HTTP protocol and use standard HTTP verbs like GET, POST, PUT, and DELETE to access resources.
    • SOAP API is an API that uses the Simple Object Access Protocol (SOAP) architectural style. SOAP APIs are based on XML and use SOAP messages to communicate between clients and servers.

    RESTful APIs are more lightweight and easier to use than SOAP APIs. However, SOAP APIs can be more powerful and can support more complex data types.

    Here is an example of how a RESTful API and a SOAP API can be used:

    • RESTful API: A weather API might use a RESTful API to provide access to weather data. The API might use the GET verb to get the current weather conditions for a specific location.
    • SOAP API: A banking API might use a SOAP API to provide access to bank account information. The API might use the SOAP message to request the balance of a specific bank account.
  28. What is the difference between a JSON API and a XML API?

    • JSON API is an API that uses the JavaScript Object Notation (JSON) data format. JSON is a lightweight data format that is easy to read and write.
    • XML API is an API that uses the Extensible Markup Language (XML) data format. XML is a more complex data format than JSON, but it can be used to represent more complex data structures.

    JSON APIs are more lightweight and easier to use than XML APIs. However, XML APIs can be more powerful and can support more complex data types.

    Here is an example of how a JSON API and an XML API can be used:

    • JSON API: A weather API might use a JSON API to provide access to weather data. The API might return a JSON object with the current weather conditions for a specific location.
    • XML API: A banking API might use an XML API to provide access to bank account information. The API might return an XML document with the balance of a specific bank account.

     

  29. What is RESTful API?
    A RESTful API (Representational State Transfer API) is an application programming interface (API) that conforms to the constraints of the REST architectural style. REST is an acronym for Representational State Transfer, which is an architectural style for distributed hypermedia systems.RESTful APIs are based on the HTTP protocol and use standard HTTP verbs like GET, POST, PUT, and DELETE to access resources. Resources are identified by URIs (Uniform Resource Identifiers), and the data associated with a resource is returned in a format like JSON or XML.Here are some examples of RESTful APIs:

    • The GitHub API
    • The Twitter API
    • The Google Maps API
    • The Facebook API
      from flask import Flask
      
      app = Flask(__name__)
      
      @app.route('/users', methods=['GET'])
      def get_users():
          """Get a list of all users."""
          users = [
              {'id': 1, 'name': 'John Doe'},
              {'id': 2, 'name': 'Jane Doe'},
          ]
          return jsonify(users)
      
      @app.route('/users/<int:user_id>', methods=['GET'])
      def get_user(user_id):
          """Get a specific user by ID."""
          user = {'id': user_id, 'name': 'John Doe'}
          return jsonify(user)
      
      if __name__ == '__main__':
          app.run(debug=True)
      

      This code defines two RESTful APIs:

      • /users: This API returns a list of all users.
      • /users/<int:user_id>: This API returns a specific user by ID.

      The GET method is used to retrieve data from the API, the POST method is used to create new data, the PUT method is used to update existing data, and the DELETE method is used to delete data.

      The data returned by the API is in JSON format. JSON is a lightweight data-interchange format that is easy to read and write.

  30. What is the difference between a GraphQL API and a RESTful API?

    • Querying: GraphQL APIs use a single query language to fetch data, while RESTful APIs use different verbs for different types of requests. For example, a GraphQL API might use the following query to fetch the name and age of a user:
    • query {
        user(id: 1) {
          name
          age
        }
      }

      A RESTful API might use the following HTTP requests to fetch the same data:

      GET /users/1
      GET /users/1/name
      GET /users/1/age
      • Data fetching: GraphQL APIs allow clients to specify exactly the data that they need, while RESTful APIs return all of the data for a resource. This can make GraphQL APIs more efficient, as clients only need to fetch the data that they need.
      • Data modeling: GraphQL APIs are designed to be data-driven, while RESTful APIs are designed to be resource-driven. This means that GraphQL APIs are better suited for applications where the data is the most important part of the API.
      • Complexity: GraphQL APIs can be more complex to develop than RESTful APIs. However, GraphQL APIs can also be more powerful and flexible.

      In general, GraphQL APIs are a good choice for applications where the data is the most important part of the API. RESTful APIs are a good choice for applications where the resources are the most important part of the API.

      Here is a table that summarizes the key differences between GraphQL APIs and RESTful APIs:

    • Feature GraphQL API RESTful API
      Querying Single query language Different verbs for different types of requests
      Data fetching Clients specify exactly the data that they need Clients fetch all of the data for a resource
      Data modeling Data-driven Resource-driven
      Complexity More complex to develop Less complex to develop
      Best for Applications where the data is the most important part of the API Applications where the resources are the most important part of the API

       

     

July 18, 2023

SpringBoot Interview Questions

  1. What is Spring Boot?
    – Spring Boot makes it easy to create stand-alone, production-grade Spring-based applications by providing a convention-over-configuration approach.
    Spring Boot is a powerful framework designed to simplify the bootstrapping and development of Spring applications. Here are some of its most notable features:

    1. Auto-Configuration: Spring Boot can automatically provide configuration for application functionality common to many Spring applications based on the libraries on the classpath.
    2. Standalone: Spring Boot applications are stand-alone and web servers can be embedded in the application. This makes it easy to deploy and run Spring Boot applications without needing an external server.
    3. Production Ready: Spring Boot has built-in features like health checks and metrics, which makes it easy to monitor and manage production applications.
    4. No Code Generation: Spring Boot does not generate code and there is absolutely zero requirement for XML configuration.
    5. Opinionated Defaults: Spring Boot gives you a set of default settings, libraries, and configurations so you can get started quickly without needing to figure out what’s the best way to set up a Spring application.
    6. Spring Boot Initializr: A web-based tool that allows users to easily bootstrap a new Spring Boot application, generating a basic project structure, Maven/Gradle build files, and application properties.
    7. Embedded Web Server Support: Provides options to have embedded Tomcat, Jetty, or Undertow servers, eliminating the need for external server setups.
    8. Spring Boot Actuator: Provides production-ready features such as monitoring, metrics, auditing, and more.
    9. Spring Boot CLI: This command-line tool can be used to run and test Spring Boot applications from a console.
    10. Flexible Configuration: Spring Boot allows developers to configure their application using a properties file, YAML, environment variables, or command-line arguments.
    11. Profiles: Enables the separation of parts of the configuration and makes it available only in certain environments, thus allowing for different configuration setups (e.g., dev, test, prod).
    12. Logging: Provides pre-configured logging via SLF4J and Logback. Developers can also easily switch to other logging solutions if needed.
    13. Integrated Data Access: Simplified database access and connection pooling with support for a wide range of relational and NoSQL databases.
    14. Developer Tools: Features like automatic restart of the application upon file changes and browser live-reload capabilities speed up the development process.
    15. Security: Integration of Spring Security makes it easier to secure web applications and RESTful services.
    16. Externalized Configuration: Spring Boot provides the ability to externalize and manage application configurations for different environments without modifying the application’s binary.
    17. Admin Features: Web-based or shell-based admin features for managing and monitoring Spring Boot applications.
    18. Web Application: Simplified Spring MVC setup with view templates, static web resources, form bindings, and more.
    19. Extensibility: Spring Boot provides a lot of extensions for building services and other types of web modules.
    20. Cloud Ready: Easy integration with Spring Cloud, making it a great choice for building microservices and cloud-native applications.
  2. What are the benefits of using Spring Boot?
    – Spring Boot makes it easy to create stand-alone, production-grade Spring applications.
    – Spring Boot provides a number of features that make it easier to develop, test, and deploy Spring applications.
    – Spring Boot is based on the principle of “convention over configuration,” which means that it provides default configurations and settings that can be overridden as needed.
    – Spring Boot has a large community of users and developers, which means that there is a lot of support available.
  3. What are the Spring Boot key components?
    • The Spring Boot starter dependencies are a set of Maven dependencies that provide the basic functionality for a Spring Boot application.
    • The Spring Boot Actuator is a set of endpoints that provide management and monitoring information about a Spring Boot application.
    • The Spring Boot CLI is a command-line tool that can be used to create, run, and manage Spring Boot applications.
    • The Spring Boot documentation is a comprehensive resource that provides information on all aspects of Spring Boot.
  4. Why Spring Boot over Spring?
    • Spring Boot is a more lightweight framework than Spring, which makes it easier to learn and use.
    • Spring Boot provides a number of features that make it easier to develop, test, and deploy Spring applications.
    • Spring Boot is based on the principle of “convention over configuration,” which makes it easier to configure Spring applications.
    • Spring Boot has a large community of users and developers, which means that there is a lot of support available.
  5. What are the basic annotations that Spring Boot offers?
    • The @SpringBootApplication annotation is the main annotation that is used to configure a Spring Boot application.
    • The @Component annotation is used to mark a class as a Spring component.
    • The @Configuration annotation is used to mark a class as a Spring configuration class.
    • The @Bean annotation is used to declare a bean in a Spring application.
    • The @Autowired annotation is used to inject dependencies into a Spring bean.
  6. What is Spring Boot dependency management?
    • Spring Boot dependency management is a feature that allows you to declare the dependencies that your Spring Boot application needs in the pom.xml file.
    • Spring Boot dependency management will automatically download and install the dependencies that your application needs.
    • Spring Boot dependency management also provides a number of features that make it easier to manage dependencies, such as version management and dependency conflict resolution.
  7. Explain what dependency injection is in springboot.
    Dependency Injection (DI) is one of the core principles upon which the Spring Framework is built. It is a design pattern that facilitates the inversion of control, which means that objects are given their dependencies rather than creating them internally. This results in a decoupled, modular, and more testable codebase.

    Explanation:

    In a standard application without dependency injection, components and services often create or look up their dependencies. This creates tight coupling between components and makes them harder to test or reuse. With DI, components declare their dependencies (typically via constructor arguments, properties, or annotations), and a container or framework (like Spring) provides those dependencies. This helps in:

    1. Decoupling: Components are not responsible for finding or creating their dependencies.
    2. Flexibility: Dependencies can be easily swapped or mocked for testing.
    3. Configuration Management: Configuration can be centralized, and objects can be wired up with different configurations for different scenarios.
    4. Life Cycle Management: The framework/container can manage the entire life cycle of beans including their creation, initialization, destruction, and more.

      Spring Boot Dependency Injection Examples:

      1. Constructor-based Injection: Here, dependencies are provided through a class constructor.
        @Service
        public class OrderService {
            private final UserRepository userRepository;
        
            @Autowired
            public OrderService(UserRepository userRepository) {
                this.userRepository = userRepository;
            }
        
            // Other methods
        }
        

        Note: In modern Spring versions, if a class has a single constructor, the @Autowired annotation can be omitted, and Spring will use that constructor by default.

      2. Setter-based Injection: Dependencies are provided through setters.
        @Service
        public class OrderService {
            private UserRepository userRepository;
        
            @Autowired
            public void setUserRepository(UserRepository userRepository) {
                this.userRepository = userRepository;
            }
        
            // Other methods
        }
        
      3. Field-based Injection: Directly injecting into fields without setters. This approach is less recommended as it makes the code harder to unit-test without a Spring context.
        @Service
        public class OrderService {
            @Autowired
            private UserRepository userRepository;
        
            // Other methods
        }
        
      4. Qualifier Annotation: When there are multiple beans of the same type and you need to specify which bean to wire, you can use the @Qualifier annotation.
        @Service
        public class OrderService {
            private final DataSource dataSource;
        
            @Autowired
            public OrderService(@Qualifier("mainDataSource") DataSource dataSource) {
                this.dataSource = dataSource;
            }
        
            // Other methods
        }
        
  8. Explain to me the problem IOC is solving.
    Inversion of Control (IoC) is a design principle that addresses the challenges of creating more modular, flexible, and testable software. Before diving into the solution IoC provides, let’s first understand the problem it aims to solve.

    The Problem:

    1. Tight Coupling: In traditional application development, objects often create or find their dependencies directly. This tight coupling makes the components hard to reuse, test, and maintain.Example: Imagine a car (Car) object that creates its own engine (Engine) instance.
      public class Engine {
          public void start() {
              // Start engine
          }
      }
      
      public class Car {
          private Engine engine;
      
          public Car() {
              this.engine = new Engine();
          }
      }
      

      In the example above, the Car class is tightly coupled to a specific Engine. This makes it challenging to replace Engine with a different implementation or to mock the engine during testing.

    2.  Configuration Sprawl: When instantiating and configuring objects directly within other objects, configuration details can be scattered throughout the application. This can lead to duplication and make the system harder to evolve.
    3. Lifecycle Management: Objects might have specific lifecycles. Manually managing these lifecycles can become cumbersome, especially in large applications.

    How IoC Solves the Problem:

    1. Decoupling through Dependency Injection: Rather than objects creating their own dependencies, they receive them from an external source (like an IoC container). This is known as Dependency Injection (DI), a form of IoC.Example:
      public class Car {
          private Engine engine;
      
          public Car(Engine engine) {
              this.engine = engine;
          }
      }
      

       

      Here, the Car doesn’t create its Engine. Instead, it’s supplied with an engine. This makes it possible to provide different engine implementations or mock engines for testing.

    2. Centralized Configuration: IoC allows configuration details to be centralized (e.g., in XML files, annotations, or Java configurations). This centralization reduces duplication and provides a single point of truth.Example using Spring:
      <!-- Spring XML Configuration -->
      <bean id="engine" class="com.example.Engine" />
      
      <bean id="car" class="com.example.Car">
          <constructor-arg ref="engine"/>
      </bean>
      

       

    3. Managed Lifecycle: An IoC container can manage the lifecycle of objects, from instantiation to destruction. This includes handling singleton/shared instances, initializing beans, and cleaning up resources.Example: With Spring, you can have the IoC container call lifecycle methods:
      @Component
      public class Engine {
          
          @PostConstruct
          public void initialize() {
              // Initialization code
          }
      
          @PreDestroy
          public void cleanup() {
              // Cleanup code
          }
      }
      

      In essence, IoC flips the traditional flow of control. Instead of objects controlling their own dependencies, a container or framework takes on the responsibility. This inversion leads to software that’s more modular, easier to test, and more resilient to change.

      Here, the initialize method is called after the Engine bean is created, and cleanup is called before it’s destroyed.

  9. Explain what IOC containers are in Java Spring Boot.
    Inversion of Control (IoC) is a principle where the control flow of a program is inverted: instead of the application code controlling the flow, the external framework or container does. In the context of the Spring Framework, the IoC container is responsible for instantiating, configuring, and assembling objects (known as beans in Spring terminology).

    Explanation:

    The IoC container receives metadata from XML files, annotations, or Java configuration classes, and then uses this metadata to create and manage the lifecycle of the beans. The main tasks of the IoC container are:

    1. Instantiating the Bean: Creating an object from its definition.
    2. Wiring the Beans: Connecting beans together, which means setting properties and injecting dependencies.
    3. Managing the Bean’s Lifecycle: Calling initialization and destruction methods where they’re defined.
    4. Configuring the Beans: Applying aspects, proxies, and other post-processing features.

    There are two primary types of IoC containers in Spring:

    1. BeanFactory: This is the basic container, providing fundamental support for DI. It’s lightweight and meant for simple use-cases.
    2. ApplicationContext: This is a more advanced container, built on top of BeanFactory. It provides additional features such as event propagation, declarative mechanisms to create a bean, integration with AOP (Aspect-Oriented Programming), and more. In most Spring-based applications (including Spring Boot apps), ApplicationContext is used more often than BeanFactory.

    Spring Boot and IoC Container:

    Spring Boot simplifies the use of the IoC container by eliminating most of the boilerplate configuration. With features like auto-configuration and component scanning, Spring Boot makes it easier to create, wire, and manage beans with minimal explicit configuration.

    Examples:

    1. Creating a Bean using Annotations:
      @Component
      public class HelloWorld {
          public String sayHello() {
              return "Hello, World!";
          }
      }
      
    2. Injecting a Dependency using Autowiring:
      @Service
      public class MessageService {
          private final HelloWorld helloWorld;
      
          @Autowired
          public MessageService(HelloWorld helloWorld) {
              this.helloWorld = helloWorld;
          }
      
          public void showMessage() {
              System.out.println(helloWorld.sayHello());
          }
      }
      
    3. Using ApplicationContext in a Spring Boot Application:
      @SpringBootApplication
      public class MyApp {
          public static void main(String[] args) {
              ApplicationContext context = SpringApplication.run(MyApp.class, args);
              MessageService messageService = context.getBean(MessageService.class);
              messageService.showMessage();
          }
      }
      
  10. Can we create a non-web application in Spring Boot?
    • Yes, you can create a non-web application in Spring Boot.
    • To do this, you need to exclude the web dependency from the pom.xml file.
    • You can also use the @SpringBootApplication annotation with the annotation attribute set to ‘false’.
  11. Is it possible to change the port of the embedded Tomcat server in Spring Boot?
    • Yes, it is possible to change the port of the embedded Tomcat server in Spring Boot.
    • To do this, you need to set the server.port property in the application.properties file.
    • For example, to set the port to 8081, you would set the server.port property to 8081.
  12. What is the default port of tomcat in spring boot?
    • The default port of tomcat in spring boot is 8080.
    • This means that if you do not specify a port in the application.properties file, the embedded Tomcat server will listen on port 8080.
  13. What are the different ways to configure Spring Boot?
    • There are three main ways to configure Spring Boot:
      • Using the application.properties file
      • Using the @Configuration class
      • Using the Spring Boot CLI
  14. What are the different ways to run a Spring Boot application?
    • There are three main ways to run a Spring Boot application:
      • Running the application as a Java application
      • Running the application as a Spring Boot JAR file
      • Running the application as a Docker container
  15. What are the different ways to test a Spring Boot application?
    • There are three main ways to test a Spring Boot application:
      • Unit testing
      • Integration testing
      • End-to-end testing
  16. How is Spring Boot different from Spring MVC?
    Spring Boot is a framework built on top of Spring to simplify its setup and usage, whereas Spring MVC is a web framework in the Spring ecosystem.
  17. What are Spring Boot starters?
    Starters are templates that contain a collection of all the relevant transitive dependencies a user needs to start a specific kind of project.
  18. What’s the advantage of Spring Boot’s “Opinionated Defaults”?
    They reduce the developer’s effort in decision-making and configuration.
  19. Explain Spring Boot’s @SpringBootApplication annotation?
    It’s a combination of @Configuration, @EnableAutoConfiguration, and @ComponentScan.
  20. How do you customize Spring Boot’s banner?
    By creating a banner.txt file in the src/main/resources directory or setting a banner.location property.
  21. How does Spring Boot handle properties/env variables?
    Using @Value annotation or by injecting the Environment object.
    Spring Boot provides a comprehensive and flexible way to handle properties. The framework offers several layers of property sources and conventions that make configuration easy and intuitive. Here’s a detailed breakdown of how Spring Boot handles properties:

    1. Externalized Configuration: Spring Boot allows you to externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments, among others, to externalize configuration.
    2. application.properties and application.yml:
      • Spring Boot looks for these files at the root of the classpath (like in src/main/resources).
      • These files can be used to define default properties.
    3. Profile-specific Properties:
      • Spring Boot lets you define properties specific to a profile (e.g., application-dev.properties for a dev profile).
      • These properties are only activated when the corresponding profile is active.
    4. Property Precedence:
      • Properties defined can be overridden. For instance, properties passed as command-line arguments override those defined in application.properties
      • Spring Boot has a specific order in which it considers property values, ranging from command-line arguments (highest precedence) to application.properties or application.yml in the jar (lowest precedence).
    5. Environment Properties:
      • Environment variables can also be used as properties. For example, a variable named SPRING_DATASOURCE_URL would map to the spring.datasource.url property in the application.
    6. Using the @Value Annotation:
      • You can bind properties directly to fields in your beans using the @Value("${property.name}") annotation.
        @Value("${custom.property}") 
        private String customProperty;
    7. Type-safe Configuration (Configuration Properties):
      • Instead of using the @Value annotation, you can bind properties to POJOs annotated with @ConfigurationProperties. This method is type-safe and offers additional benefits like validation and code-completion in IDEs.
        @ConfigurationProperties(prefix="custom")
        public class CustomProperties {
            private String property;
            // getters and setters
        }
        
    8. Placeholder Resolution:
      • Spring Boot can replace placeholders in properties and other parts of your configuration (e.g., ${another.property}).
    9. Relaxed Binding:
      • Spring Boot uses a “relaxed” strategy for binding property names, so spring.datasource.url, spring.datasource-url, SPRING_DATASOURCE_URL, and spring.datasource_url would all match the spring.datasource.url property.
  22. What is YAML? How is it related to Spring Boot?
    YAML is a human-readable data format. Spring Boot supports YAML for property configuration.
  23. Describe Profiles in Spring Boot.
    In Spring Boot, profiles provide a way to segregate parts of your application’s configuration and make it available only in certain environments. It’s a core feature of the Spring framework that has been deeply integrated into Spring Boot, allowing developers to easily manage environment-specific properties and beans.Here’s a detailed description of profiles in Spring Boot:

    1. Purpose:
      • Profiles are used when you want to apply specific configuration settings only in a specific environment. For instance, you might have different data sources for development and production or you might want to enable certain features only in the development environment.
    2. Activation:
      • Profiles can be activated in various ways:
        • Through the spring.profiles.active property (e.g., in application.properties or as a command-line argument).
        • Setting the SPRING_PROFILES_ACTIVE environment variable.
        • Using the SpringApplication.setAdditionalProfiles(...) method programmatically.
    3. Profile-specific Configuration Files:
      • You can define properties specific to a profile in separate configuration files. For example, application-dev.properties will only be applied when the dev profile is active.
      • Similarly, for YAML files, you could use application-dev.yml.
    4. Defining Beans Conditionally:
      • You can define Spring beans that are conditionally created based on which profiles are active using the @Profile annotation:
        @Profile("dev")
        @Bean
        public DataSource dataSource() {
            return new EmbeddedDatabaseBuilder().build();
        }
        
    5. Multiple Profiles:
      • Multiple profiles can be active at once. This allows you to compose configurations from multiple sources.
      • For example, you might have a cloud profile that’s used for any cloud provider and a aws profile that’s specific to AWS. You can activate both profiles simultaneously.
    6. Default Profiles:
      • If no profiles are explicitly activated, the default profile will be used.
      • This can be useful to apply certain configurations when no other profiles are active.
    7. Profile-specific Logging:
      • Log configurations can be profile-specific as well. For instance, you might want more detailed logging in a development environment compared to production.
    8. Negating Profiles:
      • You can define beans that are created when a profile is not active using the “!” notation:
        @Profile("!prod")
        @Bean
        public DataSource dataSource() {
            // This bean will be created when the 'prod' profile is NOT active
        }
        
    9. Application Arguments:
      • Profiles can be activated via command-line arguments when running the Spring Boot application. For instance:
        java -jar myapp.jar --spring.profiles.active=prod
        
  24. How do you activate a Spring profile?
    Using spring.profiles.active property.
  25. What is Spring Boot Actuator?
    It provides production-ready features to monitor and manage a Spring Boot application.
  26. Mention a few Actuator endpoints.
    /health, /info, /metrics, /env.
  27. How does Spring Boot handle database migrations?
    Using tools like Flyway or Liquibase.
  28. What’s the use of @EntityScan?
    It’s used to specify the base packages where JPA will scan for entities.
  29. How can you run a Spring Boot application?
    Using the SpringApplication.run() method.
  30. How can you customize Spring Boot’s embedded servers?
    By modifying server.* properties (e.g., server.port).
  31. Describe Spring Boot’s Data JPA starter.
    It provides key dependencies for Hibernate, Spring Data, and JPA.
  32. What’s the use of @RepositoryRestResource?
    It exposes JPA entities directly as REST endpoints.
  33. How does Spring Boot handle AOP?
    By using Spring AOP and spring-boot-starter-aop.
  34. What are Spring Boot’s initializers?
    They provide a web-based UI to generate Spring Boot projects.
  35. How can you override default properties in Spring Boot?
    By specifying them in application.properties or application.yml.
  36. How does Spring Boot support microservices?
    With Spring Cloud, which provides tools to build microservice architectures.
  37. Explain Spring Boot’s @RestController vs @Controller.
    @RestController is a shorthand for @Controller + @ResponseBody.
  38. How to enable transaction management in Spring Boot?
    With @EnableTransactionManagement and by using @Transactional on methods.
  39. How to handle exceptions in Spring Boot?
    Using @ControllerAdvice and @ExceptionHandler.
  40. Explain the Spring Boot testing support.
    It supports JUnit and provides spring-boot-starter-test with utilities like MockMvc.
  41. How can you produce a standalone Java application using Spring Boot?
    By packaging the app as a jar with embedded Tomcat, Jetty, or Undertow.
  42. What are Spring Boot build plugins?
    They help in packaging executable jars/wars, e.g., spring-boot-maven-plugin.
  43. How to exclude a particular package from Component Scan?
    With @ComponentScan(excludeFilters = @Filter).
  44. How can you modify the default location of application.properties?
    Using spring.config.location property.
  45. Explain embedded servers in Spring Boot.
    Spring Boot supports Tomcat, Jetty, and Undertow as embedded servers, which means applications can run as standalone apps.
  46. How can you change the default port in Spring Boot?
    By setting server.port in application.properties.
  47. Describe Spring Boot’s @Conditional
    It indicates a component is only eligible for registration when a specific condition matches.
  48. What is the use of @SpringBootTest?
  • It signals that the context should be a SpringApplication and loads all registered beans.
  • @SpringBootTest is an annotation provided by Spring Boot that is used for integration testing. It helps to bootstrap the entire container (depending on the provided configuration), so you can test the application in scenarios close to the actual use.Features of @SpringBootTest:
    1. Autoconfigure Spring Boot Application: It automatically configures your application based on the provided configuration and starts the application context.
    2. Web Environment: You can specify the type of web environment to use (e.g., MOCK, RANDOM_PORT, DEFINED_PORT, or NONE).
    3. Properties: You can define or override properties for the test environment.

    Examples of using @SpringBootTest:

    1. Basic Usage:
      @SpringBootTest
      class MyApplicationTests {
      
          @Test
          void contextLoads() {
          }
      }
      

      This test ensures that the application context loads without any issues.

    2. Using a Random Port: If your application starts a web server, you can start it on a random port to avoid port conflicts during testing:
      @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
      class MyWebApplicationTests {
          
          @Autowired
          TestRestTemplate restTemplate;
      
          @Test
          void testHomeEndpoint() {
              String response = restTemplate.getForObject("/", String.class);
              assertEquals("Hello World", response);
          }
      }
      
    3. Using a Mock Web Environment: For web applications, you may want to avoid starting a server altogether and just use the mock servlet environment:
      @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
      class MyWebMockTest {
      
          @Autowired
          MockMvc mockMvc;
      
          @Test
          void testEndpoint() throws Exception {
              mockMvc.perform(MockMvcRequestBuilders.get("/"))
                     .andExpect(status().isOk())
                     .andExpect(content().string("Hello World"));
          }
      }
      
    4. Overriding Properties: You can override properties for specific test scenarios:
      @SpringBootTest(properties = {"custom.property=value"})
      class PropertyOverrideTest {
          //...
      }
      
    5. Using with @ActiveProfiles: To activate certain profiles during testing, you can combine it with @ActiveProfiles:
      @SpringBootTest
      @ActiveProfiles("test")
      class MyProfileTest {
          //...
      }
      

      The @SpringBootTest annotation simplifies integration testing for Spring Boot applications by setting up and tearing down the application context and providing various utilities and configurations specific to the testing phase.

35. How can you serve static content in Spring Boot?

  • By placing it in the /public, /resources, /static, or /META-INF/resources directories.
    In Spring Boot, serving static content is straightforward and requires minimal configuration due to its opinionated defaults. Here’s how you can serve static content in a Spring Boot application:

    1. Default Static Content Locations:

    By default, Spring Boot serves static content from the following locations inside your project:

    • /META-INF/resources/
    • /resources/
    • /static/
    • /public/

    For instance, if you place an index.html file inside the src/main/resources/static/ directory of your Spring Boot application, you can access it by visiting http://localhost:8080/index.html after starting your application.

    2. Custom Static Content Locations:

    If you want to customize the static content locations, you can do so by configuring the spring.resources.static-locations property. For example, to serve static content from a custom-dir directory:

    spring.resources.static-locations=classpath:/custom-dir/
    

     

36. Describe the hierarchy of application.properties in Spring Boot.

  • @TestPropertySource, @SpringBootTest.properties, and inside the JAR are examples of levels.

    In Spring Boot, the application.properties (or its YAML counterpart, application.yml) file is the primary means for configuring application settings. Spring Boot provides a flexible system of looking for this configuration file in various locations and offers a hierarchy that determines the order of precedence for reading these configurations.

    Here’s the hierarchy for application.properties locations, starting from the highest precedence:

    1. Command Line Parameters:
      • Properties passed as command-line arguments, e.g., java -jar app.jar --server.port=8081
    2. Properties from SPRING_APPLICATION_JSON:
      • Properties can be passed as a JSON string via the SPRING_APPLICATION_JSON environment variable.
    3. Java System Properties:
      • Properties set using -D argument, e.g., java -Dserver.port=8081 -jar app.jar
    4. OS Environment Variables:
      • Operating System specific environment variables. For example, a property named server.port can be sourced from an environment variable named SERVER_PORT.
    5. Configuration files outside the packaged jar:
      • A application.properties or application.yml located in the same directory from which the application is run.
      • Or in a ./config sub-directory of the directory from which the application is run.
    6. Configuration files inside the packaged jar:
      • A application.properties or application.yml at the root of the classpath, typically inside the src/main/resources directory.
      • Or in a /config package or directory inside the jar.
    7. Configuration properties on the classpath:
      • A application.properties or application.yml located in the classpath root.
    8. Default properties:
      • Properties set using SpringApplication.setDefaultProperties.

    Profile-specific properties:

    Along with the above, Spring Boot allows for profile-specific property files. These are named like application-{profile}.properties or application-{profile}.yml. Profile-specific property files have precedence over the default application.properties or application.yml but are ordered by the same precedence rules mentioned above.

    For example, if a dev profile is active, application-dev.properties outside the jar will override the application.properties outside the jar, but both will be overridden by any value passed as a command-line argument.

    Conclusion: The hierarchy and the ability to source configurations from various locations allow for a high degree of flexibility. You can have default settings packaged within your application and override them for different environments using external files or even command-line arguments. This makes it easier to manage configurations across different deployment scenarios without changing the packaged application.

37. What is a Spring Boot Fat JAR?

  • A JAR that contains embedded dependencies, including the server.

38. What are the main advantages of using Spring Boot?

  • Rapid development, production-ready setups, convention over configuration, and no code generation.

39. How do you enable debug logging in Spring Boot?

  • Set logging.level.root=DEBUG in application.properties.

40. Explain the importance of the pom.xml file in Spring Boot.

  • It defines project metadata, dependencies, and build plugins for Maven-based projects.

41. What’s the purpose of @EnableAutoConfiguration?

  • It enables automatic configuration based on libraries present in the classpath.

42. How does Spring Boot simplify database connectivity?

  • With auto-configured data sources and spring-boot-starter-data-jpa.
    Spring Boot significantly simplifies database connectivity by providing a number of automated configurations, sensible defaults, and integration with popular Java database tools and libraries. Here’s how Spring Boot aids in easing database connectivity:

    1. Auto-configuration:
      • When you add a database-related dependency (like an embedded database or a JPA implementation), Spring Boot attempts to set up a database connection based on the libraries present in the classpath.
    2. Data Source Configuration:
      • Spring Boot can provide a lot of database configuration automatically, based on the properties defined in the application.properties or application.yml files.
      • For instance, just by defining properties like spring.datasource.url, spring.datasource.username, and spring.datasource.password, you can configure a data source without any manual bean definitions.
        spring.datasource.url=jdbc:mysql://localhost:3306/mydb
        spring.datasource.username=root
        spring.datasource.password=secret
    3. Embedded Databases:
      • Spring Boot provides out-of-the-box support for H2, HSQL, and Derby embedded databases. When any of these is on the classpath, Spring Boot automatically sets up an embedded database for you.
    4. Connection Pooling:
      • Connection pooling libraries like HikariCP, Tomcat, and DBCP2 are automatically configured when they’re on the classpath.
      • By default, if HikariCP is on the classpath, it’s chosen as the primary connection pool due to its performance and concurrency benefits.
        spring.datasource.hikari.maximum-pool-size=10
    5. JPA & Spring Data JPA:
      • By including the Spring Data JPA starter, Spring Boot auto-configures Hibernate as the default JPA provider.
      • With minimal properties set, Spring Boot sets up Hibernate, scans entities, and sets up a default EntityManager.
    6. Repository Support:
      • With Spring Data JPA, you can create interfaces extending CrudRepository or JpaRepository and Spring Boot automatically provides the implementation at runtime, enabling CRUD operations on entities without writing the boilerplate code.
    7. Database Initialization:
      • Spring Boot can auto-detect SQL scripts (like schema.sql and data.sql) and run them at startup to initialize the database.
      • It also supports using tools like Flyway or Liquibase for database version control and migration by simply including their dependencies and configuration.
      • Description: Spring Boot can automatically run SQL scripts on startup for database initialization.
      • Example: If you place a file named schema.sql in the src/main/resources directory, Spring Boot will execute it on startup.schema.sql:
    8. Profile-based Configuration:
      • Different application-{profile}.properties files can be used for different environments. This means you can have separate configurations for development, staging, and production, making it easy to switch between databases based on the active profile.
    9. JDBC Template:
      • If you’re using plain JDBC, Spring Boot provides auto-configuration for the JdbcTemplate, making it easier to interact with relational databases without managing connections and exceptions manually.
        @Autowired
        JdbcTemplate jdbcTemplate;
        
        public int getCountOfBooks() {
            return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM book", Integer.class);
        }
        
    10. Metrics & Health Indicators:
      • When used with Spring Boot Actuator, it provides metrics and health checks related to database connectivity, helping in monitoring and managing the application in production environments.
    11. Exception Translation:
      • Spring Boot integrates the persistence exception translation mechanism of Spring, which translates lower-level SQL and database exceptions into Spring’s DataAccessException, making it easier to handle database-related errors in a consistent way.In essence, Spring Boot removes much of the boilerplate code traditionally associated with setting up and managing database connections in a Spring application. This allows developers to focus on their domain logic rather than the intricacies of database setup and connectivity.

43. What is the importance of @Repository in Spring Boot?

  • Marks the class as a DAO, throws specific exceptions, and can be scanned by Spring.

44. How can you specify the active profile while running a Spring Boot application?

  • Using --spring.profiles.active=myprofile during startup.

45. How can you secure a Spring Boot application?

  • With spring-boot-starter-security and @EnableWebSecurity.
    Securing a Spring Boot application is made simpler with the integration of Spring Security. Spring Security provides a comprehensive security solution for Java applications, handling authentication, authorization, and other security concerns. Here’s how you can secure a Spring Boot application, along with illustrative examples:

    1. Add Spring Security Dependency:

    First and foremost, you’ll need to add the Spring Security starter to your pom.xml (if using Maven):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
  • Basic Authentication:

    By merely including the above dependency, Spring Boot will set up basic authentication for all routes with a default user named “user” and a generated password that’s displayed in the console on startup.

    Example: Accessing any endpoint without authentication will return a 401 Unauthorized. Use the provided username and password in the request header or when prompted by the browser to authenticate.

    3. Configure Custom User Details:

    You can configure user details and their roles in memory or retrieve them from a database.

    Example – In-memory Authentication:

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("admin").password("{noop}admin123").roles("ADMIN")
                .and()
                .withUser("user").password("{noop}user123").roles("USER");
        }
    }
    

    Authorize Requests:

    You can specify which routes or endpoints are accessible by which roles.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
            .antMatchers("/").permitAll()
            .and().formLogin();
    }
    

     

     

46. What is a CommandLineRunner in Spring Boot?

  • It lets you run specific code once the application context is fully started.

47. Describe the structure of a typical Spring Boot project.

  • It follows the Maven/Gradle directory structure, with main application code in src/main/java and resources in src/main/resources.

48. How can you customize the Jackson ObjectMapper in Spring Boot?

  • By defining a @Bean of type ObjectMapper in a configuration class.

49. What are the benefits of using the Spring Boot DevTools?

  • Automatic restart, live reload, and developer-friendly properties.

50. What is spring-boot-starter-parent?

  • It’s a parent POM providing dependency and plugin management for Spring Boot applications.
July 31, 2022

Introduction

What is Flask?

Flask is a web development framework. It provides a lot libraries for building lightweight web applications in python. Flask is considered by many as a micro-framework due to the fact that it only provides the essential components – things like routing, request handling, sessions, and so on. It provides you with libraries, tools, and modules to develop web applications like a blog, wiki, or even a commercial website. It’s considered “beginner friendly” because it doesn’t have boilerplate code or dependencies which can distract from the primary function of an application. Data handling handling for example, the developer can write a custom module or use an extension. 

What is Flask used for?

Flask is mainly used for backend development, but it makes use of a templating language called Jinja2 which is used to create HTML, XML or other markup formats that are returned to the user via an HTTP request. 

Note that in this series of tutorial, we’ll be using Flask as a backend framework and React as a frontend framework.

June 28, 2022