programming

Coding Questions

Top 100 coding questions in Python

I have shared basic to advanced-level interview questions and answers. BASIC LEVEL (1-20) 1. Reverse a String 2. Check if a string is a palindrome 3. Find Factorial 4. Fibonacci Sequence 5. Check Prime Number 6. Find Maximum in List 7. Remove Duplicates from List 8. Count Character Frequency 9. Check Anagram 10. Find Missing Number in Array 11. Find Second Largest Number 12. Check Armstrong Number 13. Sum of Digits 14. Find GCD 15. Find LCM 16. Count Vowels in String 17. Check if String Contains Only Digits 18. Find Intersection of Two Lists 19. Find Union of Two Lists 20. Check Balanced Parentheses INTERMEDIATE LEVEL (21-60) 21. Two Sum Problem 22. Find Duplicates in Array 23. Move Zeros to End 24. Rotate Array 25. Find Majority Element 26. Binary Search 27. Merge Sorted Arrays 28. First Non-Repeating Character 29. Implement Stack using List 30. Implement Queue using List 31. Reverse Linked List 32. Detect Cycle in Linked List 33. Find Middle of Linked List 34. Implement Binary Tree 35. Tree Traversals 36. Maximum Depth of Binary Tree 37. Validate Binary Search Tree 38. Find All Permutations 39. Find All Subsets 40. Longest Substring Without Repeating Characters 41. Container With Most Water 42. 3Sum Problem 43. Merge Intervals 44. Find Peak Element 45. Search in Rotated Sorted Array 46. Word Break Problem 47. Longest Palindromic Substring 48. Implement LRU Cache 49. Find Kth Largest Element 50. Top K Frequent Elements ADVANCED LEVEL (51-80) 51. Serialize and Deserialize Binary Tree 52. Find Median from Data Stream 53. Regular Expression Matching 54. Wildcard Matching 55. Edit Distance 56. Coin Change Problem 57. Longest Increasing Subsequence 58. Maximum Subarray Sum (Kadane’s Algorithm) 59. House Robber 60. Climbing Stairs 61. Unique Paths 62. Decode Ways 63. Word Search 64. Number of Islands 65. Course Schedule (Cycle Detection) 66. Minimum Window Substring 67. Sliding Window Maximum 68. Trapping Rain Water 69. Largest Rectangle in Histogram 70. Merge K Sorted Lists 71. Sort Colors (Dutch National Flag) 72. Find First and Last Position 73. Spiral Matrix 74. Set Matrix Zeros 75. Valid Sudoku 76. N-Queens Problem 77. Sudoku Solver 78. Evaluate Reverse Polish Notation 79. Implement Trie (Prefix Tree) 80. Design Twitter ADVANCED ALGORITHMS & DATA STRUCTURES (81-100) 81. LFU Cache 82. Find Median in Two Sorted Arrays 83. Longest Consecutive Sequence 84. Alien Dictionary 85. Minimum Path Sum 86. Palindrome Partitioning 87. Reconstruct Itinerary 88. Minimum Height Trees 89. Word Ladder 90. Count of Smaller Numbers After Self 91. Maximal Rectangle 92. Burst Balloons 93. Serialize and Deserialize N-ary Tree 94. Flatten Nested List Iterator 95. Max Points on a Line 96. Word Search II 97. Candy Crush (1D) 98. Employee Free Time 99. Race Car 100. Swim in Rising Water

Top 100 coding questions in Python Read More »

Master Python by Building 8 Classic Games

Learning Python by building games is one of the most effective ways to develop real programming skills. Each game teaches specific concepts while keeping you engaged and motivated. This roadmap will guide you from a beginner to a confident Python developer. Solutions will not be provided directly—you are encouraged to struggle, think, and build your own logic. This is where real learning happens. Avoid using AI to solve the problems; do it yourself to truly master Python. 1. Hangman What it teaches: String manipulation, lists, loops, basic I/O The game: Player guesses letters to reveal a hidden word. Each wrong guess adds a body part to the hangman. Six wrong guesses = game over. How to start: Key hint: Store the display as a list of characters, making it easy to reveal letters: [‘_’, ‘_’, ‘t’, ‘_’, ‘o’, ‘_’] 2. Rock Paper Scissors What it teaches: Random module, dictionaries for logic, game loops The game: Player picks rock, paper, or scissors. The computer picks randomly. Winner determined by classic rules. How to start: Key hint: Use a dictionary to encode what each choice beats instead of nested if-statements. This makes adding Lizard and Spock trivial. 3. Quiz Game What it teaches: Lists of dictionaries, file I/O, data organization The game: Present multiple-choice questions, track correct answers, show final score, and percentage. How to start: Key hint: Use a list of dictionaries to store questions. Later, read from a JSON file for easy question management. 4. Blackjack (21) What it teaches: Classes, complex state management, multiple functions The game: Get closer to 21 than the dealer without going over. Aces count as 1 or 11. Dealer hits to 16, stands on 17+. How to start: Key hint: Handle aces by starting them as 11, then converting to 1 if the hand busts. Use a function to calculate hand value. 5. Tic-Tac-Toe What it teaches: 2D lists, pattern checking, basic AI The game: Two players alternate placing X and O on a 3×3 grid. First to get three in a row wins. How to start: Key hint: Check win conditions by examining all rows, then all columns, then two diagonals. For AI, start with random moves, then add logic to block the opponent. 6. Mastermind What it teaches: Counting algorithms, feedback systems, careful logic The game: The computer picks a secret code of 4 colors. Player guesses, gets feedback on exact matches (right color, right position) and partial matches (right color, wrong position). How to start: Key hint: Calculate exact matches first, then count remaining colors that appear in both secret and guess for partial matches. 7. Dice Rolling Game (Yahtzee) What it teaches: Counter class, scoring logic, categorization The game: Roll 5 dice, choose which to keep, re-roll others (up to 3 rolls). Score based on combinations: three of a kind, full house, straight, etc. How to start: Key hint: Use collections.Counter to count dice values. Each scoring rule is a separate function that takes the dice list. 8. Battleship What it teaches: Multiple grids, coordinate systems, validation, and hidden information The game: Player and computer each place ships on a 10×10 grid. Take turns guessing coordinates to sink the opponent’s ships. How to start: Key hint: Use separate grids for the player’s board, the computer’s board, and tracking guesses. Convert input like “B4” to coordinates: row = ord(‘B’) – ord(‘A’), col = 3. Quick Start Guide Project Order Recommendation Beginner: Start with Hangman → Rock Paper Scissors → Quiz Game Intermediate: Tic-Tac-Toe → Mastermind → Blackjack Advanced: Dice Game → Battleship By the time you complete all eight games, you’ll have solid Python fundamentals and a portfolio of working projects. Now pick your first game and start coding!

Master Python by Building 8 Classic Games Read More »

10 Python Libraries That Build Dashboards in Minutes

Let me tell you something—I’ve wasted countless hours building dashboards from scratch, wrestling with JavaScript frameworks, and questioning my life choices. Then I discovered these Python libraries, and honestly? My life got so much easier. If you’re a data person who just wants to visualize your work without becoming a full-stack developer, this post is for you. 1. Streamlit I’ll be honest—Streamlit changed everything for me. You literally write Python scripts and get beautiful web apps. No HTML, no CSS, no JavaScript headaches. That’s it. That’s the tweet. Three lines and you’ve got an interactive dashboard. It’s perfect for quick prototypes and sharing models with non-technical stakeholders who just want to click buttons and see results. 2. Dash by Plotly When I need something more production-ready, I reach for Dash. It’s built on top of Flask, Plotly, and React, but you don’t need to know any of that. You just write Python and get gorgeous, interactive dashboards. The learning curve is slightly steeper than Streamlit, but the customization options are incredible. I’ve built entire analytics platforms with this thing. 3. Panel Panel is my go-to when I’m already working in Jupyter notebooks and don’t want to rewrite everything. It works seamlessly with practically any visualization library you’re already using—matplotlib, bokeh, plotly, you name it. What I love is that I can develop right in my notebook and then deploy it as a standalone app. No context switching, no rewriting code. 4. Gradio If you’re doing anything with machine learning models, Gradio is a gift from the tech gods. I’ve used it to demo models to clients, and the “wow factor” is real. You can wrap your model in a UI with literally 3 lines of code. Image classification? Text generation? Audio processing? Gradio handles it all and makes you look like a wizard. 5. Voilà Sometimes I just want to turn my Jupyter notebook into a dashboard without changing a single line of code. That’s where Voilà comes in. It renders your notebook as a standalone web app, hiding all the code cells. I use this all the time for presenting analysis to my team. They get to see the results and interact with widgets, but they don’t have to wade through my messy code. 6. Plotly Express Okay, technically Plotly Express isn’t a dashboard library—it’s a visualization library. But hear me out. The charts it creates are so interactive and beautiful that sometimes you don’t even need a full dashboard framework. I’ve literally built entire reports with just Plotly Express charts embedded in simple HTML. One-liners that create publication-ready visualizations? Yes please. 7. Bokeh Bokeh is for when I need fine-grained control but still want everything in Python. It’s great for creating custom interactive visualizations that feel professional and polished. The server component lets you build full applications, and I’ve used it for real-time monitoring dashboards. It handles streaming data beautifully. 8. Taipy I only recently discovered Taipy, but I’m kicking myself for not finding it sooner. It’s designed specifically for data scientists who need to build production applications. What sets it apart is how it handles scenarios and pipelines. If your dashboard needs to run complex workflows or manage different data scenarios, Taipy makes it surprisingly straightforward. 9. Solara Solara is all about reactive programming—your dashboard automatically updates when your data changes. It’s built on top of React but you never touch JavaScript. I love using this for dashboards that need to feel really responsive and modern. The component-based approach makes it easy to build complex interfaces without losing your mind. 10. Shiny for Python If you’re coming from the R world, as I did, Shiny for Python will feel like coming home. It brings the reactive programming model of R Shiny to Python, and it works beautifully. I appreciate how it encourages you to think about reactivity and state management from the start. The resulting dashboards feel polished and professional. My Honest Take Here’s what I’ve learned after building dashboards with all of these: there’s no “best” library. It depends on what you’re trying to do. The beautiful thing is that they’re all Python. You don’t need to become a web developer to build impressive, interactive dashboards. You just need to know Python and have something interesting to show. So pick one, build something, and stop overthinking it. I spent way too long agonizing over which library to learn first. Just start with Streamlit, you’ll have something running in 10 minutes, and you can always learn the others later. Now go build something cool and show it off. The world needs more data people who can actually visualize their insights.

10 Python Libraries That Build Dashboards in Minutes Read More »

If You Could Make Python Run 20× Faster Without Changing Your Logic?

If You Could Make Python Run 20× Faster Without Changing Your Logic?

Look, I love Python. I really do. It’s elegant, readable, and honestly? It just makes sense. But let’s be real for a second—it’s also slow. Like, painfully slow sometimes. I remember this one time I was processing a massive CSV file for a data analysis project. My script was chugging along, and I literally had time to make coffee, check my emails, and question all my life choices before it finished. I thought, “There’s got to be a better way, right?” Turns out, there is. And no, I’m not talking about rewriting everything in C++ or learning Rust (though props to you if you do). I’m talking about squeezing serious performance gains out of Python without touching your actual logic. Sounds too good to be true? Stick with me. The Reality Check Nobody Talks About Here’s the thing most tutorials won’t tell you: Python is an interpreted language, and that’s both its blessing and its curse. The same flexibility that makes it so easy to write also makes it… well, not exactly a speed demon. But before you start panicking and thinking you need to rewrite your entire codebase, let me share what I’ve learned from years of making slow Python code fast. The Low-Hanging Fruit (That Actually Works) 1. NumPy: Your New Best Friend If you’re doing anything with numbers—and I mean anything—and you’re not using NumPy, we need to talk. Seriously. I once rewrote a loop that was processing temperature data. The original version with regular Python lists took about 45 seconds. The NumPy version? Less than 2 seconds. Same logic, same result, just vectorized operations instead of loops. It’s almost embarrassing how much faster this is. 2. List Comprehensions Over Loops This one’s subtle but powerful. Python’s list comprehensions aren’t just more Pythonic—they’re actually faster because they’re optimized at the C level. The performance difference grows with your data size. And honestly? The comprehension version just looks cleaner too. 3. Use the Right Data Structure (Please) I spent weeks once debugging a performance issue that turned out to be… wait for it… using a list when I should’ve used a set. Checking if an item exists in a list is O(n). In a set? O(1). If I had a time machine, I’d go back and slap myself for not knowing this sooner. The Game Changers Codon: The Actual Game Changer Okay, this is where my mind was genuinely blown. Have you heard of Codon? It’s a Python compiler—not an interpreter, a compiler—that converts Python to native machine code. And get this: it can give you performance that’s basically on par with C/C++. I was skeptical at first. Like, really skeptical. But then I tried it on a bioinformatics script I’d been working on. Standard Python took about 12 minutes to process a genomic dataset. With Codon? 38 seconds. I checked three times because I thought I’d broken something. Here’s the wild part—you can use Codon’s JIT decorator in your regular Python code: That’s it. One import, one decorator. The @jit decorator compiles that function to native machine code the first time it runs, and every subsequent call is blazing fast. I’m talking 50-100x speedups for computational loops. The beautiful part? It’s literally just Python. You’re not writing in some weird subset of the language or learning new syntax. You write normal Python, add @jit, and Codon does the heavy lifting. The catch? It’s still relatively new (MIT developed it), and while it supports most of Python’s standard library, some third-party packages might not work yet. But for computational tasks, data processing, or anything CPU-intensive, where you’re writing your own logic? This is the real deal. I’ve started sprinkling @jit decorators on my performance-critical functions, and it’s become my go-to solution before considering any major rewrites. Numba: Magic When You Need It Numba is wild. You literally just add a decorator to your function, and it compiles it to machine code. It’s especially amazing for numerical computations. That @jit decorator can give you 10-100x speedups depending on what you’re doing. It’s not magic—it’s a JIT compiler—but it feels like magic. The Honest Truth About Caching Okay, real talk: I used to think caching was for people who were bad at writing efficient code. I was wrong. So, so wrong. Python’s functools.lru_cache is ridiculously easy to use and can make recursive functions or repeated calculations blazing fast. Without caching, calculating fibonacci(35) takes forever. With caching? Instant. It’s one line of code for potentially massive gains. When to Actually Care About This Stuff Here’s my honest advice: don’t optimize prematurely. I’ve wasted hours optimizing code that ran once a week and took 3 seconds. That’s 3 seconds I’ll never get back, and probably 2 hours of optimization time I definitely won’t. But when you’re dealing with: Then yeah, these techniques are absolutely worth it. The Bottom Line Python doesn’t have to be slow. Sure, it’ll never beat C for raw speed, but you know what? Most of the time, we don’t need C-level performance. We need code that’s fast enough and still maintainable. I’ve seen 20x speedups from just: And the best part? My code still looks like Python. It’s still readable. I can still come back to it in six months and understand what’s happening. So yeah, if someone told past-me that I could make my Python code 20x faster without rewriting the logic, I would’ve called them a liar. But here we are. And honestly? It feels pretty good.

If You Could Make Python Run 20× Faster Without Changing Your Logic? Read More »

what is python

What is Python?

Python is a widely-used programming language that’s known for being beginner-friendly. Created by Guido van Rossum and first released in 1991, it has become one of the most popular languages in the world. Python is commonly used for: What can you do with Python? Why choose Python? Important things to know How Python syntax differs from other languages How do we define a function? Simple Class creation.

What is Python? Read More »

python cisco free test

Learn Python and Earn Free Badges with Cisco NetAcad

Are you ready to start your Python programming journey? I’ve found something exciting to share with you – two completely free Python courses from Cisco that will help you master Python fundamentals and earn valuable badges to showcase your skills! Why Learn Python? Python is one of the most popular and beginner-friendly programming languages in the world. Whether you want to build websites, analyze data, automate tasks, or dive into artificial intelligence, Python is your perfect starting point. The best part? You can learn it for free and get certified along the way! Free Python Courses with Badges Cisco Networking Academy offers two comprehensive Python courses that are completely free and provide you with official badges upon completion: 1. Python Essentials 1 Perfect for: Absolute beginners with no programming experience This course covers the fundamentals of Python programming and helps you build a strong foundation. You’ll learn: Get Started: Python Essentials 1 Course 2. Python Essentials 2 Perfect for: Those who’ve completed Python Essentials 1 or have basic Python knowledge This intermediate course takes your skills to the next level with: Get Started: Python Essentials 2 Course What You’ll Get 100% Free – No hidden costs or subscription fees Official Badges – Showcase your achievements on LinkedIn and your resume Self-Paced Learning – Study whenever and wherever you want Hands-On Practice – Real coding exercises and projects Industry Recognition – Cisco is a globally recognized technology leader How to Get Started Why I Recommend These Courses Unlike many other free resources that leave you wandering without direction, these Cisco courses provide structured learning paths with clear goals. The interactive exercises help you practice what you learn immediately, and the badges give you something tangible to show potential employers or clients. Whether you’re looking to switch careers, enhance your current job skills, or simply explore programming as a hobby, these courses are an excellent starting point. Ready to Start? Don’t wait! Your Python programming journey begins today. Click on the course links, enroll for free, and start earning those valuable badges. The skills you gain will open doors to countless opportunities in the tech world. Remember: Every expert programmer started exactly where you are now. Comment below if you get any other free resource, I will make a post

Learn Python and Earn Free Badges with Cisco NetAcad Read More »

Real questions from my recent Python Developer interview

Python Interview Questions and Answers

Recently, I appeared for an interview, and I am sharing the questions and answers that were asked during the session. 1. Fibonacci Series in Python The Fibonacci series is a sequence in which each number is the sum of the two preceding numbers. Example (Loop Method): Example (List Generation): 2. List Comprehension vs Tuple Comprehension List Comprehension A concise way to create a list. ✔ Stores all values in memory. Tuple Comprehension (Generator Expression) Python does not have tuple comprehension. But you can write: This creates a generator, not a tuple.To convert to a tuple: 3. What is a Generator? A generator is a function or expression that returns values one at a time using the yield keyword. Example: Why Generators? 4. SQL Query to Find 2nd Highest Salary Method 1: Using ORDER BY + LIMIT (MySQL/PostgreSQL) Method 2: Using MAX() Function If the salary table is separate 5. How Python Manages Memory? Python uses multiple internal systems: Private Heap Memory All Python objects and data structures live in a private heap. Memory Manager Allocates space for objects automatically. Garbage Collector Uses: When no reference objects are deleted. Object Caching Mechanism Python caches: To improve performance. 6. How to Use Oracle Database with Python To connect Python with Oracle, use the cx_Oracle module. Install the library: Connection Example: Why cx_Oracle? 7. How do you handle if the Django Project suddenly gets high traffic? When Django receives sudden high traffic, I handle it by using caching to reduce server load, adding a load balancer to distribute requests, and scaling the application by running multiple instances. I also optimize database queries, move heavy tasks to background workers, use a CDN for static files, and monitor the system to detect issues early.

Python Interview Questions and Answers Read More »

Python object image

How to Check if an Object Has an Attribute in Python

I can’t tell you how many times I’ve run into this scenario: I’m working on a Python project, confidently accessing an object’s attribute, and boom—AttributeError crashes my program. Sound familiar? This happens all the time when you’re dealing with different object types. Maybe you’re working with user accounts where some users have premium features and others don’t. Or perhaps you’re building an API that receives varying data structures. Whatever the case, knowing how to safely check for attributes is essential. Let me walk you through the different ways I handle this in my own code. Why Bother Checking for Attributes? Here’s a real scenario I dealt with recently: I was building a user management system where regular users had basic info (name, email), but premium users had additional fields like subscription_type and discount_rate. If I tried to access user.subscription_type a regular user object, Python would throw an AttributeError and my whole application would crash. Not ideal, especially in production! That’s why we need to check first. The Different Ways to Check (And When I Use Each) 1. hasattr() – My Go-To Method Honestly, this is what I use 90% of the time. It’s clean, simple, and does exactly what you need: I love hasattr() because it’s readable. When someone else looks at my code, they immediately understand what I’m doing. 2. getattr() – Check and Grab in One Go Sometimes you don’t just want to check if an attribute exists—you want to use it right away. That’s where getattr() shines: I find this super useful when I’m setting up configuration objects or dealing with optional features. Instead of writing an if-statement, I just provide a sensible default. 3. Try-Except – When You Need More Control Sometimes I need to do something more complex when an attribute doesn’t exist. That’s when I reach for try-except: This approach is great when the attribute access itself might trigger some side effects, or when you want to log the missing attribute for debugging. 4. dir() – For When You’re Exploring To be honest, I mostly use dir() When I’m debugging or exploring an unfamiliar library: It’s not something I put in production code, but it’s invaluable during development. A Real Example from My E-commerce Project Let me show you how I used these techniques in an actual project. I was building a shopping cart system with different user tiers: The beauty here is that process_order() it doesn’t need to know what type of cart it’s dealing with. It just checks for the capability and acts accordingly. Works for Methods and Properties Too By the way, these techniques aren’t just for regular attributes. They work perfectly with methods and properties: What I’ve Learned Over Time After years of Python development, here are my rules of thumb: When to use what: Things to avoid: Here’s a mistake I made early on: Wrapping Up Learning to check for attributes properly has saved me countless hours of debugging and prevented so many crashes. The key takeaway? Choose the right tool for the job: Start with hasattr() For most cases, it’s Pythonic, readable, and gets the job done. You can always refactor to something more complex if you need to. What’s your preferred method? Have you run into any tricky situations with attribute checking? I’d love to hear about them in the comments!

How to Check if an Object Has an Attribute in Python Read More »

image of many to many relation in Django

Many-to-Many Relations with ‘through’ in Django

Hey there! If you’ve been working with Django for a while, you’ve probably used many-to-many relationships. They’re great, right? But have you ever felt like you needed more control over that relationship? Like, you want to store extra information about the connection between two models? That’s exactly where the through parameter comes in, and trust me, once you get the hang of it, you’ll wonder how you ever lived without it. What’s a Many-to-Many Relationship Anyway? Before we dive into the through stuff, let’s quickly recap. A many-to-many relationship is when multiple instances of one model can be related to multiple instances of another model. Think about it like this: You get the idea! The Basic Many-to-Many Setup Usually, you’d set up a many-to-many relationship like this: Django automatically creates an intermediate table behind the scenes to handle this relationship. Easy peasy! But here’s the thing – what if you want to store more information about the enrollment? Like when the student enrolled, what grade they got, or whether they’ve completed the course? Enter the ‘through’ Parameter This is where the magic happens. The through The parameter lets you create your own intermediate model with whatever extra fields you want. Here’s how it works: See what we did there? We told Django: “Hey, use this Enrollment model to manage the relationship between Student and Course.” Why Would You Want to Do This? Here are some real-world scenarios: 1. Social Media App: You have Users and Groups. The membership can have a role (admin, moderator, member) and a join date. 2. E-commerce Platform Products and Orders. The intermediate table stores quantity, price at time of purchase, and any discounts applied. 3. Project Management Employees and Projects. You want to track the role of each employee in each project and the hours they’ve worked. 4. Recipe App: Recipes and Ingredients. The intermediate table holds the quantity and measurement unit for each ingredient. How to Work with Through Models Creating Relationships You can’t use the simple add() method anymore. You need to create instances of your “through” model directly: Querying Relationships You can query in both directions: Filtering with Extra Fields Here’s where it gets really cool: Important Things to Remember 1. ForeignKey Fields are Required. Your through model MUST have foreign keys to both models in the relationship. 2. unique_together. Usually, you want to prevent duplicate relationships, so use unique_together in the Meta class. 3. No Direct add(), create(), or set(). When using a through model, you can’t use these shortcuts. You have to create instances of the through model directly. 4. Removal Still Works. You can still use remove() and clear(): Complex Example Let’s say you’re building a music streaming app: Now you can do cool stuff like: Common Problems to Avoid 1. Forgetting to Create the Through Instance. Don’t try to use add() – it won’t work! 2. Not Using unique_together. You might end up with duplicate relationships, which can cause weird bugs. 3. Making the Through Model Too Complex: Keep it focused on the relationship. If you’re adding tons of fields, maybe they belong in one of the main models instead. 4. Circular Import Issues. If you reference models as strings (like through=’Enrollment’), make sure the model is defined in the same file or properly imported. When NOT to Use Through You don’t always need a through model! Use the simple many-to-many if: Remember: premature optimization is the root of all evil. Don’t overcomplicate things if you don’t need to! Wrapping Up The through parameter in Django’s many-to-many relationships is super powerful. It gives you complete control over intermediate tables and lets you model complex real-world relationships accurately. Start simple, and add complexity only when you need it. Your future self (and your teammates) will thank you for keeping things as straightforward as possible while still meeting your requirements. Now go ahead and build something awesome! And remember, every complex relationship in your database is just a bunch of simple relationships working together.

Many-to-Many Relations with ‘through’ in Django Read More »

Building Real-World APIs with FastAPI

Building Real-World APIs with FastAPI

When I first started working with FastAPI, I was blown away by how quickly I could get a simple API up and running. But as my projects grew from proof-of-concepts to production systems serving thousands of requests per second, I learned that writing scalable FastAPI applications requires more than just decorating functions with @app.get(). Today, I want to share the patterns and practices I’ve developed over the past few years building APIs that actually scale in the real world. Why FastAPI? Before diving deeper, let me quickly justify why FastAPI has become my go-to framework. It’s not just hype—FastAPI genuinely delivers on its promises: But speed and features mean nothing if your codebase becomes unmaintainable at scale. The Layered Architecture Pattern The first mistake I made was putting everything in a single main.py file. It worked great for tutorials, but became a nightmare in production. Here’s the architecture I now use for every project: This structure separates concerns clearly: API endpoints handle HTTP, services contain business logic, and models represent data. It’s not over-engineering—it’s sustainable engineering. Dependency Injection: Your Best Friend FastAPI’s dependency injection system is powerful, but it took me a while to appreciate it fully. Here’s how I use it for database sessions: But dependencies aren’t just for databases. I use them for: The beauty is that dependencies are testable and composable. You can mock them easily in tests without touching your endpoint code. Configuration Management Done Right Hard-coded configuration is a recipe for disaster. I use Pydantic’s BaseSettings for environment-based config: This pattern gives you: Async All the Way (But Wisely) FastAPI supports async endpoints, but mixing sync and async code incorrectly can kill performance. Here’s what I learned: Use async when: Stick with sync when: Don’t make everything async just because you can. Profile and measure. Error Handling and Custom Exceptions Early on, I let exceptions bubble up and relied on default error messages. Bad idea. Now I use custom exception handlers: This gives you consistent error responses across your API and makes debugging much easier. Request Validation with Pydantic Pydantic schemas are more than just data containers—they’re your first line of defense against bad data: The validation happens automatically before your endpoint code runs. Invalid requests never reach your business logic. Background Tasks for Better Response Times Don’t make users wait for tasks that don’t need to be completed before responding: For heavier workloads, integrate with Celery or RQ, but background tasks are perfect for lightweight async operations. Testing Strategies That Work I use TestClient for integration tests and dependency overrides for mocking: The ability to override dependencies makes testing incredibly clean—no monkey patching required. Database Session Management One of the trickiest aspects is managing database sessions correctly. Here’s my pattern: Never create global database sessions. Always use dependency injection and let FastAPI handle the lifecycle. Monitoring and Observability You can’t improve what you don’t measure. I add middleware for request logging and timing: For production, integrate with proper monitoring tools like Prometheus, DataDog, or New Relic. Rate Limiting for Protection Protect your API from abuse with rate limiting. I use slowapi: Caching for Performance For expensive operations or frequently accessed data, implement caching: For distributed caching, Redis is your friend. Use libraries like aioredis for async support. Final Thoughts Building production-grade APIs with FastAPI isn’t about following every pattern blindly—it’s about understanding which patterns solve real problems in your specific context. Start simple, profile your application, identify bottlenecks, and apply these patterns where they make sense. Over-engineering early is just as bad as under-engineering. The patterns I’ve shared here have saved me countless hours of debugging and refactoring. They’ve helped me build APIs that handle millions of requests per day with confidence. FastAPI gives you the tools, but it’s up to you to use them wisely. Happy coding!

Building Real-World APIs with FastAPI Read More »

Scroll to Top