Search This Blog

Thursday, 24 July 2025

Rest APIs using Python

Understanding REST APIs

A REST API is like having a conversation with a web server using the HTTP protocol. You send an HTTP request, and the server replies with an HTTP response.

 


KEY COMPONENTS IN A REST API INTERACTION ARE

A. HTTP Request: In simple words it means: You Ask for Something

Every request includes:

  • Method: What you want to do (GET, POST, PUT, DELETE)
  • URL: The address of the resource (/users, /posts/1)
  • Headers: Extra info like content type (application/json)
  • Body: Data sent (for POST, PUT, etc.)

Example:



B. HTTP Response: Server Replies

A response includes:

  • Status Code: Was it successful? (200 OK, 404 Not Found, 201 Created)
  • Headers: Info about the response
  • Body: The actual data (often JSON)


Key methods used in HTTP Operations


WORKING WITH REST APIs IN PYTHON

What Is urllib?

urllib is part of Python’s standard library and includes submodules like:

  • urllib.request: for opening and reading URLs
  • urllib.parse: for encoding query parameters
  • urllib.error: for handling exceptions

No installation needed — it’s ready to go out of the box! 

We shall use this library to work with Rest APIs

Please refer to the following trinket to see an example on GET, POST, PUT, DELETE operations in Python





Wednesday, 23 July 2025

OOPs in Python

Python supports rich object-oriented programming (OOP) features that promote modularity, scalability, and readability. In this article, we’ll explore core OOP concepts using Python’s syntax and conventions—ideal for building GUI apps, REST APIs, and creative projects.

Classes: They are like a template to create new objects. Similar to the blueprint of a house plan created by the architect.


Constructor: 

Every class has a constructor. This ensures that the object is created and loaded in the application memory with its settings as provided in the constructor. This is similar to the architect of the house instructed the contractor how to lay the foundation with which material and how it needs to be placed etc.

This is done using python's built-in function __init__(self).
This is a special function which will be invoked by python at runtime. You can see the above example with the __init__(self, <parameters>)
where,
self : here indicates the current context of the object created

Inheritance
Inheritance lets one class absorb properties and behaviors of another.


Syntax: 

class Child(Parent):
            ... your code here ...

Let's take the example of senior developer:



** NOTE: Please note, the above class does not have __init__()

Here, we need to understand, that until the parent class is constructed the child class cannot be constructed. Hence order of construction of object in execution, in the case of inheritance is
1.  parent __init__() 
2. child __init__()

CASE: In case the parent constructor has parameters apart from self, then how can these be supplied in inhheritance case?

ANS: Use super().__init__(parent-parameter-values)

Hence the above code will be modified to call the parent class constructor as follows:



Access Specifiers:
The following conventions are used to specify access.


See the following example:
Here instance properties are created where values assigned are native to that specific object only.



Statics:These are shareable variables and function. They are invoked using

ClassName.<static_member>

See the following example:


Overriding: The concept of  changing the behaviour of a function (logic of the function) in the child class is known as overriding




Overloading: The concept of creating a function with the same name but different parameters is known as overloading. Python does not support overloading. This can be done by using *args, **kwargs kind of parametersin the function

Play around with the following trinket showing all the above explained operations as an example



Monday, 21 July 2025

Python Basics: Lambdas

 

Lambdas in Python are like mini-functions without a name, perfect for short, quick operations—think of them as the “Post-it notes” of the coding world: compact, purposeful, and disposable.

What Is a Lambda Function?

A lambda in Python is an anonymous function defined using the lambda keyword. It’s used when you need a simple function for a short period and don’t want to formally define it with def.

Syntax Breakdown

lambda arguments: expression

  • You can pass multiple arguments, but only a single expression.
  • You can’t use statements like loops or conditionals—just expressions.


def traditional_square(num):
    return num * num

square = lambda num: num * num  #defined the function
print(square(5))


Common Use Cases

Use Case

Example

        With map()    

        map(lambda x: x*2, [1, 2, 3])[2, 4, 6]

        With filter()

        filter(lambda x: x > 0, [-1, 0, 1])[1]

        With sorted()

        sorted(words, key=lambda x: len(x)) → sort by length

        Quick function

        lambda x, y: x + y



Python Basics: Dictionaries

 

What Is a Dictionary in Python?

A dictionary is a built-in data type that lets you store data in key-value pairs. Instead of accessing values by a number (like in a list), you access them by their label.

Syntax



When to Use Dictionaries

Use them when:

  • When working with Json data
  • This works well with data returned from Database / backend
  • You want fast lookup by a unique key
  • You're organizing settings, user profiles, configurations, etc

Common methods used with dictionaries




See the following code and try it yourself






Thursday, 17 July 2025

Python Functions using global and comprehension

 In the earlier article, we have seen the use of global, and the different flavors of functions in Python.

Let''s combine them and use comprehensions to reduce the total lines of code.

What are comprehensions in Python?

In Python, comprehensions are a concise and expressive way to create new sequences—like lists, sets, dictionaries, or generators—from existing iterables. They let you write elegant one-liners that would otherwise require multiple lines of loops and conditionals.

Comprehensions work like the Arabic language, read from right-to-left

🔍 Observations

  • In the above screenshot, in modify(old_emp, new_emp), the execution happens in a sequential top-to-down manner.
  • In modify_smart(old,new), the same execution happens in one-line from right to left

Let's highlight the comprehension in the modify_smart()

🔍 Investigating the above code: 

  • for emp in company_employees: Iterate over each employee name in the list.
  • new if emp == old else emp: If the employee name matches old, replace it with new; otherwise, keep it unchanged.

Python Basics: Using Globals

 What is the use of Global keyword

The global keyword is used to declare that a variable inside a function refers to a variable defined in the global scope—outside the function. Without it, Python treats variables assigned inside a function as local by default.

Each function runs in its own scope. Any changes made in it are confined within the scope of the function.

Hence, if a variable name is declared outside the function and is later modified inside the function, the modifications made inside the function will not reflect in the variable declared outside the function.

This functions similar to having a secret-lingo within friends. Outside the friends circle the same secret-lingo will not be shared. Modification to outer variables inside the functions also work in a similar way.

🔍 Understanding the above code

  • secret_lingo is a global string that holds our "secret message".
  • update_lingo() uses global secret_lingo to modify it from inside the function.
  • reveal_lingo() just prints the current value.

Let's try this with collection types. Here, we shall take the example of lists

Unlike for primary datatypes, the collection types will need the global keyword to be used only if there is an assignment operation inside the function.
For modification of collection items, removal of items, appending items to the collection use of globals keyword  is not required

No need to use global keyword in the case shown below


Reassigning the list (needs global)



Updating the list (no need of global)






Wednesday, 16 July 2025

Python Basics - Lists in Python

 A list is an ordered, mutable collection used to store multiple items in a single variable.

This is how a list looks like



Key Features

  • Ordered: Items remain in the order they were added.
  • Mutable: You can add, remove, or change elements.
  • Heterogeneous: Different data types in one list? No problem.
  • Iterable: Perfect for loops and comprehensions.

When to Use Lists

  • Dynamic datasets (to-do items, animation frames, user input)
  • Collections where items may change
  • GUI elements that update often
  • Grouping related values together

List Of Operations





Comparing Tuples Vs List








Python Basics - Understanding Tuples in Python: The Immutable Sidekick

 A tuple is an ordered, immutable collection of items. Once created, you can’t modify its contents—which makes it ideal for data that shouldn't change.

This is how a tuple is created

Unpacking a tuple





Key Features

  • Ordered: Elements maintain the order you assign.
  • Immutable: Unlike lists, you can't alter, add, or remove items.
  • Heterogeneous: Can hold different data types.
  • Hashable: Useful as dictionary keys or in sets (if all elements are hashable).

When to Use Tuples

  • To represent fixed collections, like RGB colors, coordinates, or database records.
  • As function return values to return multiple items cleanly.
  • When working with dictionaries as keys (since lists can't be keys).

Behind the Scenes

Tuples are lighter on memory and faster to access, making them perfect for performance-critical Python apps. Integrating tuples smartly can help you write cleaner and more efficient code.


Comparison between the collection types : List Vs Tuples



Python Basics : Handling Exceptions - Try-Except-Finally

 In Python exceptions can be handled using the try-except-finally block.

This is the most basic way of handling exceptions. The purpose of the try-except-finally block is "Not to expose the internal details of the exception, But present a friendly error message to the End User"

For example, a friendly message as shown here for an internal error of  "Insert into database db-name -> table-name failed View Stacktrace : ....."

⚠️ Something went wrong. Please contact Support at some-email@some-company.


In an enterprise application, try-except-finally are not sufficient.

For every exception handling scenario, there must be two perspectives that should be considered.

1. End user perspective: This is the user who is using your application through a device / browser. He need not know the technicalities and internal workings of this application.

2. The Application Support Team Members: These are the technical staff who would be supporting the end-user in case of any issues faced. This team must have a relevant idea of the internal workings of the product.

Hence, Exception handling can be done using two best practices.

1. For the End-user: We can use the Try-Except-Finally block

2. For the Application Support Team Members: We shall have an additional strategy of using Log files / Log tables


Here, in this article we will understand the flavors of  try-except-finally to present a user-friendly error.

Syntax:


try:
    your code here
except <Error Type>:
    your code here
except <Error Type>:
    your code here
finally:
    your cleanup / closure code



FLAVORS:

Single Except block: Here the error type is Value Error. The base Error type class is known as Exception. To capture errors like key-stroke errors etc, BaseException class can also be used


 Multiple Except Blocks: To catch multiple errors, and return different friendly messages.


Except with Tuple: To return a standard message for multiple error types, add the error types to a tuple.

Catch all types of Exceptions: Use the class Exception / BaseException








Python Basics : Functions in Python

 Functions are a means to aid modular programming where reusable chunks of code are grouped together, to be created once and invoked several times.

This is the first step to modular programming which then leads to creating modules, classes and packages for re-usability. This practice is common across all languages, and Python is no exception to this rule.

This article covers flavors of creating functions in the traditional way. The same functions can be created in a language agnostic way using lambdas. This will be covered in a later article.

Syntax of a function is as follows

def function_name (arg1, arg2 ,...):

       your code here...






Tuesday, 15 July 2025

Python Basics: Control Statements

 

Control statements alter the flow of program execution in any language.

Here, we shall be exploring the if-elif-else structure.


Syntax:
 if  :
     your code..
 elif  :
    your code...
 else :
     your code...



Using the match statement

The match statement is used when there are multiple cases and need to be made more readable and maintainable.

Case _: indicates the default case / else case. This case will execute when none of the other cases are matching the condition

Syntax:
 match  
        case :
            your code ...
        case :
            your code ...
        case _:
            your code for else case

Example: 








Python Basics: Getting inputs from the end user

 This post explains how to get inputs from the end user, and the flavours of inputs that can be taken.

The predominant function here is: input() 

To get sensitive data like passwords, which should not be visible to the end user, we use the getpass package and getpass() function






Python Basics: Different ways to print an output to the console

To continue with this step, please complete the step of creating a project in PyCharm. The step by step process is shown here: Create a project in Pycharm

Syntaxes of Python are similar to english language. It is readable, simple and has minimal syntax

This post explains how to create a basic python program.

The following program shows different ways to print a value to the output console. The function used is print()


Step by Step - Creating a python project in PyCharm


Whether you're crafting a GUI calculator with Tkinter or animating turtles across your screen, PyCharm is an excellent playground for building and managing Python projects. This guide walks you through setting up your first Python project in PyCharm—from installation to execution.

Step 1: Install PyCharm

Before you start, ensure you have PyCharm installed. Here's how:

  • Head over to JetBrains PyCharm
  • Choose Community Edition (free) or Professional Edition (paid with extra features)
  • Download the installer based on your OS and follow the setup wizard

Step 2: Create a New Project

Once installed, launch PyCharm and create a new project:

  1. Open PyCharm, then click New Project from the welcome screen
  2. Choose the location for your project folder
  3. Select the Python interpreter:
  • Either use an existing interpreter or click Add Interpreter
  • Recommended: Create a virtual environment for project isolation

Step 3: Configure Virtual Environment (Optional but Recommended)

Virtual environments help keep dependencies clean and manageable.

If you’re creating a new interpreter:

  • Choose New Environment using Virtualenv
  • Set the base interpreter (usually your system Python)
  • If none is installed, the dropdown will display a download icon like so:

  • PyCharm will automatically configure the environment

Now you have an isolated workspace—perfect for experimenting!

Step 4: Create Your Python File

Now let’s add some code:

  1. Right-click the project folder in the left panel
  2. Go to New → Python File
  3. Name your file (e.g., main.py) and hit Enter
  4. Start coding!

print("Hello, PyCharm!")

Click the green play button ▶️ to run your script.


Friday, 4 July 2025

Dockerizing Angular app

 

Prerequisites

Make sure you have:

  • Angular CLI installed (npm install -g @angular/cli)
  • Docker installed and running
  • A working Angular project (ng new my-app if starting fresh)
  • These steps are for Angular apps using angular 17+
  • For earlier versions, changes in the docker file will be required

 Step 1: Build Your Angular App

ng build --configuration production

This creates a dist/ folder with your production-ready files.

Step 2: Create a Dockerfile

Create a default.conf for creating nginx custom configurations

server {
  listen 80;
  server_name localhost;

  root /usr/share/nginx/html;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

In your project root, create a file named Dockerfile:

# Stage 1: Build the Angular app
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Stage 2: Serve with Nginx
FROM nginx:alpine
COPY default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist/angular-docker-app/browser /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Replace my-app with your actual Angular project name inside dist/.

Step 3: Create .dockerignore

To keep your image lean:

node_modules
dist
.git
Dockerfile
.dockerignore

Step 4: Build the Docker Image

docker build -t angular-docker-app .

Step 5: Run the Container

docker run -d -p 8080:80 angular-docker-app

Now visit http://localhost:8080 to see your app live in a container!

Quick Tech Tips: Fastest way to Learn Xunit for Beginners

Set up xUnit with.NET 8 for effective unit testing by following these practical steps to create, write, and run tests.

Prerequisites

Before you begin, ensure you have the following installed:
  • .NET SDK 8.0 or later: Download from the official.NET website.
  • Visual Studio (recommended) or Visual Studio Code for easier development and testing.

Creating a New xUnit Project

  1. Open a terminal or command prompt and navigate to the directory where you want to create your project.
  2. Create a new xUnit test project by running the command:
    dotnet new xunit -n MyFirstUnitTests
    
    This will create a new folder named MyFirstUnitTests with the necessary xUnit references.
  3. Navigate into the project directory with:
    cd MyFirstUnitTests
    
  4. Add a class library to test. For example, create a new class library for testing:
    dotnet new classlib -n MyLibrary
    
    This command creates a project that you can later reference in your unit tests.

Writing Your First Test

  1. Add a reference to the class library:
    dotnet add reference../MyLibrary/MyLibrary.csproj
    
  2. Open the UnitTest1.cs file located in the MyFirstUnitTests directory and replace its content with your test code. Here is an example test:
    using Xunit;
    using MyLibrary;  // Replace with your class library namespace
    
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            Assert.True(true);  // Replace true with your condition
        }
    }
    
  3. Run your tests using the command:
    dotnet test
    
    This will compile your tests and execute them, providing you with feedback on which tests passed or failed.

Advanced Testing with xUnit

  • Parameterized Tests: Use the [Theory] attribute combined with [InlineData] to run multiple data variations through a single test method. Here is an example:
    [Theory]
    [InlineData(1, false)]
    [InlineData(2, true)]
    [InlineData(3, true)]
    public void IsPrimeTest(int number, bool expected)
    {
         Assert.Equal(expected, IsPrime(number));  // Implement IsPrime accordingly
    }
    

Running Tests in Visual Studio

If you are using Visual Studio, you can utilize the Test Explorer to run your tests visually:
  1. Open Test Explorer via Test > Test Explorer.
  2. Run tests by clicking the Run All button in the Test Explorer toolbar.

Thursday, 3 July 2025

Docker Compose - Web Api connecting to SQL Server container

One of the modern ways of deploying is using the Lift-And-Shift Mechanism. There are two deployment strategies used in this case

  1. Virtual Machines
  2. Containerization
In this post, we shall explore how to use Docker-Compose to containerize Web Apis that use SQL Server DBMS.

USECASE: The concerned web api needs to be deployed on a different server (container) and the DB to be deployed on a different Server (container)

This is a classic case in the deployment architecture of almost every enterprise product.

TOOLKIT:

Containerization : Multi-container in the same sub-net
Tool for Containerization: Docker-Compose

PRODUCT TECHNICAL SPECS:

API Layer: Web Api, .Net 8.0 runtime
DAL Layer: EF Core, .Net 8.0
UI Layer: Out of Scope for this post. It can be MVC Web App, Angular App, React App, even a console app etc.

DETAILS OF WEB API

Name of Api: ProductService
Model Class name: Product
DBContext Name: ProductServiceContext

MIGRATION STRATEGY

Migrating the DB to configured SQL Server Container (container name: sqlData)

This can be accomplished from scratch, in two prominent steps

  1. Steps to Scaffold Controller with EF Core
    1. Use Visual Studio Rapid Scaffolding to 
      1. install EF Core, 
      2. create actions, 
      3. create dbContext,  using code-first approach
  2. Create the DB in the Docker Container
    1. Configure connection string
    2. Create a Migration Service
    3. Configure docker-compose.yml


 STEPS TO SCAFFOLD CONTROLLER WITH EF CORE

  1. Create "Models" folder
  2. Add a class named "Product". This will be your model class, which will become a table when integrated with a DBMS like SQL Server.
    1. 7fd0ff9a81183c407c8add0949ea94ad.png
  3. Save your project and Build it.
  4. Right Click on Controllers Folder -> Add -> New Controller -> Choose (API Controller in Left Pane) -> Choose API Controller with Entity Framework Actions
    1. bf99c6d4620f8669de07d652f2e872e4.png
    2. 3a7294644c50d0abffffac80cadde245.png
    3. cd3538003f05694f9ae5f31cf4f056f1.png
    4. Click Add. This will install all required EF Core Nuget Packages and auto-generate
      1. the ProductsController,
      2. The EFCore DBContext Class named ProductServiceContext,
      3. app.config settings

To create the DB in the Docker Container, go ahead with the following steps

 

  • Create a migration.
    • Build your project
    • Set your WebApi project as the Startup project
    • Open Package Manager Console, verify that the Web Api project is the default project
      • > Add-Migration v1                           

  • Add the following code in the Program.cs file, after the line: var builder = WebApplication.CreateBuilder(args);

    • var server = builder.Configuration["DbServer"] ?? "localhost";
      var port = builder.Configuration["DbPort"] ?? "1433"; // Default SQL Server port
      var user = builder.Configuration["DbUser"] ?? "SA"; // Warning do not use the SA account
      var password = builder.Configuration["Password"] ?? "sa@12345Ok!";
      var database = builder.Configuration["Database"] ?? "ProductsDB";

      //concatenate them into a connection string
      //server, port;Initial Catalog=database;userID=user;password=password
      var connectionString = $"Server={server}, {port};Initial Catalog={database};User ID={user};Password={password};TrustServerCertificate=True;";



      builder.Services.AddDbContext<ProductServiceContext>(options =>
          options.UseSqlServer((connectionString)));


    • After the line: var app = builder.Build(); ADD THE FOLLOWING
      • DbMigrationService.MigrationInit(app);
      • Generate the class and replace with the following code
        • public class DbMigrationService
          {
              public static void MigrationInit(IApplicationBuilder app)
              {

                  using (var serviceScope = app.ApplicationServices.CreateScope())
                  {
                      try
                      {
                          serviceScope.ServiceProvider.GetService<ProductServiceContext>().Database.Migrate();
                      }
                      catch (Exception ex)
                      {
                          Debug.WriteLine(ex.Message);
                      }
                  }
              }
          }


    • Open docker-compose.yml file. Here we will create a new container that will hold the DB. Now add the following configurations. 
      •  sqldata:
              container_name: sqldata
              image: mcr.microsoft.com/mssql/server:2019-latest
              restart: always
              environment:
                  ACCEPT_EULA: "Y"
                  SA_PASSWORD: "sa@12345Ok!"
                  MSSQL_PID: Developer
              ports:
                  - "1433:1433"
      • Append the following in the productservice configuration in the docker-compose.yml
        • environment:
              DbServer: "sqldata"
              DbPort: "1433"
              DbUser: "SA"
              Password: "sa@12345Ok!"
              Database: "ProductsDB"
          depends_on:
            - sqldata

        • The above configuration should be appended as shown in the screenshot below3314ac5cf19393e23bdf7a8532b93919.png

      • Set the docker-Compose Project as your startup project. Run your application.