<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akpotaire Dennis Koko  on Medium]]></title>
        <description><![CDATA[Stories by Akpotaire Dennis Koko  on Medium]]></description>
        <link>https://medium.com/@denniskoko?source=rss-1405a7d766bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ti9gCvHfhbAWdEcOG14NSA.jpeg</url>
            <title>Stories by Akpotaire Dennis Koko  on Medium</title>
            <link>https://medium.com/@denniskoko?source=rss-1405a7d766bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:52:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@denniskoko/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hail the Pandas DataFrame, all hail the Pandas DataFrame]]></title>
            <link>https://medium.com/@denniskoko/hail-the-pandas-dataframe-all-hail-the-pandas-dataframe-a51512d5eb18?source=rss-1405a7d766bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a51512d5eb18</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Akpotaire Dennis Koko ]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 09:38:44 GMT</pubDate>
            <atom:updated>2025-04-24T09:38:44.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*mH1XirNrQ8RhN3iwihUcQQ.png" /><figcaption>Image Credit: <a href="https://www.cbc.ca/news/canada/giant-panda-cubs-politics-economics-conservation-toronto-zoo-1.3481839">https://www.cbc.ca/news/canada/giant-panda-cubs-politics-economics-conservation-toronto-zoo-1.3481839</a></figcaption></figure><p>Hail the Pandas DataFrame.<br>Hail the Pandas DataFrame.<br>All hail the Pandas DataFrame.</p><p>Imagine you have a diligent and highly skilled assistant in the world of data. This assistant is always ready to help you organize, clean, and analyze data like no one else can. You can ask them to handle complex tasks with ease, and they always have a solution. Meet the Pandas DataFrame — your loyal data companion who can handle just about any data task you throw at them. In this article, we’ll walk through all the incredible things the DataFrame can do.</p><h4><strong>The DataFrame as an Organizer: Keeping Things Neat and Tidy</strong></h4><p>Imagine your DataFrame as a meticulous organizer. It takes your messy, unordered data and transforms it into a clean, structured format. Just like a well-organized filing cabinet, your DataFrame keeps everything in neat rows and columns, which makes finding information quick and easy.</p><p><strong>Task it with: </strong><br>- Creating new columns: The DataFrame can add extra columns to your dataset whenever you need them, just like a secretary adding a new section to a report. <br>- Labeling data: It assigns meaningful names to your rows and columns, so every piece of data is clearly identified. If your data lacks names, it will happily create default labels for you.</p><h4>The DataFrame as a Data Cleaner: Getting Rid of the Junk</h4><p>The DataFrame has an uncanny ability to spot the mistakes in your data, like a keen-eyed editor catching spelling errors in a manuscript. It can clean up missing values, remove duplicates, and fix inconsistent data formats. If some data seems incomplete or incorrect, your DataFrame will step in to fix it with methods like fillna or dropna.</p><p><strong>Task it with:</strong><br>- Fixing missing values: Just like a helpful friend who notices you forgot to finish a task and takes care of it for you.<br>- Removing duplicates: If someone is cluttering your data with redundant information, the DataFrame will gently point them out and tell them to leave.<br>- Changing data types: If the numbers in your dataset are written as text, your DataFrame will take the time to convert them into actual numbers, just as someone would fix the formatting of a report.</p><h4>The DataFrame as a Transformer: Reshaping the World</h4><p>Like a shape-shifting character in a fantasy story, the DataFrame is a master at changing its form to fit the task at hand. Need your data to look different? No problem. The DataFrame can pivot, melt, and reshape your data as easily as a tailor adjusting the fit of a suit.</p><p><strong>Task it with:</strong><br>- Pivoting: Just like flipping a board game to view it from a new angle, the DataFrame can rearrange its rows and columns to give you a fresh perspective.<br>-Melt and Reshape: If your data is stored in an inconvenient format, the DataFrame will “melt” it down and then reshape it into something much more usable.</p><h4>The DataFrame as a Detective: Digging Into the Details</h4><p>Your DataFrame is a skilled detective, always digging through data to uncover hidden patterns. By grouping and aggregating data, it can reveal insights about your dataset that you didn’t even know were there.</p><p><strong>Task it with:</strong><br>- Grouping data: If you need to know how each department in a company is performing, the DataFrame can group your data by department and summarize the performance for you.<br>- Aggregating data: The DataFrame can also compute averages, sums, or other statistics on your data, like a research assistant compiling your results into one neat report.</p><h4>The DataFrame as a Social Connector: Merging Data Like a Matchmaker</h4><p>Much like a social butterfly who brings people together, your DataFrame can merge different datasets based on common columns, combining them into a single, cohesive unit. It’s like arranging a dinner party where everyone has a common interest (like a shared column) and ensures they get along perfectly.</p><p><strong>Task it with:</strong><br>- Merging DataFrames: Whether it’s an inner, left, right, or outer join, the DataFrame knows exactly how to merge datasets to make sure you get the information you need.<br>- Concatenating DataFrames: Your DataFrame can also stitch datasets together vertically or horizontally, just like a person who can seamlessly integrate into different social circles.</p><h4>The DataFrame as a Timekeeper: Dealing with Dates and Times</h4><p>Like an expert planner who can remember every meeting and deadline, the DataFrame has an exceptional talent for managing dates and times. Whether it’s extracting the day of the week, calculating time differences, or grouping data by months, the DataFrame handles time with precision.</p><p><strong>Task it with:</strong><br>- Handling dates: It can quickly convert strings into datetime objects, allowing you to perform calculations or group data by specific time periods.<br>- Time differences: If you’re working with timestamps, the DataFrame can easily calculate how much time has passed between two dates, just like a seasoned event planner calculating the time until the next big event.</p><h4>The DataFrame as an Analyst: Understanding Complex Relationships</h4><p>If you need to understand relationships within your data, your DataFrame is ready to assist. By calculating correlations and performing complex analyses, it can point out hidden connections between variables, much like a seasoned analyst connecting the dots.</p><p><strong>Task it with:</strong><br>- Calculating correlations: The DataFrame can calculate the relationship between two or more columns, helping you understand how one variable influences another.<br>- Statistical analysis: With built-in functions, the DataFrame is more than just a container for data; it’s also capable of running statistical tests or generating summary statistics that give you a deeper understanding of your data.</p><h4>The DataFrame as a Teacher: Sharing Knowledge</h4><p>When you’re ready to take your data analysis skills to the next level, the DataFrame is happy to teach. It provides comprehensive documentation, intuitive error messages, and examples that help guide you through your work, just like a helpful mentor explaining concepts with clarity and patience.</p><p><strong>Task it with:</strong><br>- Documentation: The DataFrame has an extensive documentation system, available at your fingertips, so you can always learn and grow.<br>- Clear errors: When something goes wrong, it doesn’t just leave you in the dark — it provides clear, helpful messages so you can learn from the mistake and avoid it in the future.</p><h4>The Enduring Power of the Pandas DataFrame</h4><p>At the end of the day, the Pandas DataFrame is like that incredibly efficient and reliable colleague who makes your job easier and more enjoyable. It takes care of the hard work, transforming, cleaning, and analyzing data with human-like skills and precision. Whether you’re a novice or an expert, the Pandas DataFrame is there to assist, guide, and empower you on your data journey. So, next time you work with a DataFrame, remember — you’re not just using a tool, you’re working with a capable assistant who always has your back.</p><p><strong>If this post teaches you one or two things, please take a second to hit the 👋 clap button and leave a comment with your thoughts! ❤️</strong></p><p>Hey, I am Dennis Koko and I would be so glad to connect with you on <a href="https://www.linkedin.com/in/denniskoko/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a51512d5eb18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The People in My LinkedIn Network Are More Interesting Than I Thought]]></title>
            <link>https://medium.com/@denniskoko/the-people-in-my-linkedin-network-are-more-interesting-than-i-thought-35f8c4f34c54?source=rss-1405a7d766bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f8c4f34c54</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Akpotaire Dennis Koko ]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 14:13:02 GMT</pubDate>
            <atom:updated>2025-04-10T14:13:02.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a2d64tBwgqCeiI3U.jpg" /><figcaption>Image Credit: <a href="https://linkedinriches.com/turn-linkedin-profile-views-sales/">https://linkedinriches.com/turn-linkedin-profile-views-sales/</a></figcaption></figure><p>Who are the people in your LinkedIn network?</p><p>If you are like me, you have 500+ LinkedIn connections, you send connection requests, you receive connection requests. <br>But do you know the demographic distribution of your connections?</p><p>I used to think my LinkedIn 1st degree network consists of 90% Software Engineers. <br>My connection data obtained from LinkedIn revealed otherwise. <br>Software Engineers in my network are a little above 18%.</p><p>We all should get a copy of our data from LinkedIn and analyse it (or at least upload it to some ConnectionRM dashboard) for demographic insights.</p><p>In this latest Medium article, I detail my recent analysis of my LinkedIn connection data.</p><h4>Obtaining the Data</h4><p>I requested a copy of my data by going to Settings, then Data Privacy. <br>I had to request for a copy of all my data since the option to only request for connection data seems missing. <br>But I’m glad I requested for all the data since the other data are interesting data I would analyse some other time. <br>Inside the Zip file provided by LinkedIn is a Connections.csv file containing my connections data. <br>This data was loaded into a Pandas DataFrame for exploratory and statistical analysis.</p><h4>Exploring the Data</h4><p>As typical of a data analysis project, I begun by exploring the data.<br>My exploration revealed that there are 875 rows of connection data in the dataset. And the data is in seven columns. The columns are as follows:</p><ol><li>First Name</li><li>Last Name</li><li>URL</li><li>Email Address</li><li>Company</li><li>Position</li><li>Connected On</li></ol><p>The total memory usage of the dataset is a meager 48.0+ KB.</p><p>Next, I analysed the columns for missing values. <br>My analysis revealed there are 41 connections with no first names, last names, and LinkedIn URLs. <br>Then there are no emails in the email column for 842 connections. This is expected since connections usually make their email private. Private emails are not usually exported by LinkedIn. <br>For the Company column, there are 66 missing entries. This means 66 connections haven’t added the company they work to their LinkedIn profiles. <br>For the Position column, there are 65 missing entries. This also mean 65 connections haven’t added their current position to their LinkedIn profiles. <br>There were zero missing values in the Connected On column. Since this data is auto generated by LinkedIn on the data the connection was made, it would have been odd to see a missing entry in this column.</p><p><strong>How can First Name, Last Name, and URL columns all have the same 41 missing entries?</strong></p><p>This deserved some investigation. <br>My investigation revealed that each of those 41 entries also cut across the remaining columns (Email Address, Company, Position) except Connected On. <br>My conclusion is that while I was connected to these people at some point, they have either closed their LinkedIn accounts or LinkedIn have by themselves sent them packing. Their information is therefore no longer available for export.</p><h4>Data Cleaning</h4><p>Since there are 41 connections who are no longer connections, the rows associated with those connections were duly removed reducing the total connection data to 834. The Email Address column is mostly null, it was therefore also removed.</p><p>But we should note that while there are no more rows with missing First Name, Last Name, and URL columns, and the Email Address column no longer exists, there are still rows with missing Company, and Position columns. <br>For the Company column, as it stands, there are no company data for 25 connections. <br>For the Position column, as it stands, there are no position data for 24 connections.</p><h4>Data Transformation</h4><p>The Connected On column was transformed from a string object to a datetime object.</p><h4>Descriptive Statistics</h4><p>My descriptive analysis confirmed that the connection count is now 834. Before data cleaning, it was 875.<br>It also revealed that in the years I’ve begun my LinkedIn connection journey, connections have only happened for 298 days. <br>Of those 298 days, I recorded the most connection on 2023–10–18. On that day, I recorded 23 connections. <br>The earliest day connection s were made was 2021–07–30 while the most recent day connections were made was 2025–04–07.</p><p>The following are the top days connections were made:</p><ol><li>2023–10–18 with a record of 23 connections</li><li>2023–03–02 with a record of 19 connections</li><li>2023–01–21 with a record of 15 connections</li><li>2023–03–03 with a record of 15 connections</li><li>2023–02–21 with a record of 14 connections</li></ol><p>Below are two charts showing consecutive days I recorded connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iltkBxyuHx0bjtt_WBcWYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UR1OJFXtcw8W4uzIUILkIg.png" /></figure><p>The highest of those days was from 2023–02–27 to 2023–03–22. That is a total of 24 days. During that time period, over 160 connections was made.</p><p>The lowest of those days was from 2023–07–07 to 2023–07–13. That’s a total of 7 days. During that time period, less than 20 connections were made.</p><h4>Key Questions</h4><p><strong>Question 1:</strong><em> Which companies in my network have the most connections (i.e., the companies where I have the most connections)?</em></p><p>This chart answers the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DweQE0H562AnIVoyXnW5A.png" /></figure><p>The top company in the chart is Freelance. Is Freelance a company? No. <br>The next top company is Microsoft. Microsoft is therefore the company I’m most connected to. Other notable companies in the chart are Amazon, MTN Nigeria, CDI, CDW, and Infosys.</p><p><strong>Question 2: </strong><em>Which job titles/positions do I have the most connections in?</em></p><p>This chart answers the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hI-CbbweCYLVr3yJMD6DNw.png" /></figure><p>The top position in the chart is Software Engineer. 66 of my connections work in that role. That’s about 8% of my connections. <br>Then I have 24 connections with the title Senior Software Engineer comprising 2.96% of my connections.</p><p><strong>Question 3: </strong><em>How has my connections grown over time?</em></p><p>The following charts answer the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xe6LsyXXsTIErLq5y_YboQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g27ho7qmsIbU14Nyb_so0Q.png" /></figure><p>The two charts together illustrate a significant surge in connection activity beginning in late 2022 and peaking in March 2023. The first chart, which tracks daily connections over time, shows minimal growth from mid-2021 to 2022, followed by a sharp and dense cluster of activity in early to mid-2023. This period included several days I recorded double-digit connection counts, indicating a highly active phase. After mid-2023, my connection activity declined sharply and returned to a relatively stable, low level similar to the pre-growth phase.</p><p>The second chart, aggregating monthly data, reinforces this trend by highlighting March 2023 as the peak month with over 160 connections. The trendline demonstrates a rapid build-up to this peak, followed by a steady decline and eventual plateau. Combined, these charts suggest there was a time I had a focused burst of networking outreach which led to substantial connection growth within a short period before leveling off.</p><p><strong>Question 4:</strong> <em>Which month and year was I most connected?</em></p><p>Analysis revealed that March 2023 was the year I had the most connections. In that month, I made 170 connections.</p><p><strong>Question 5: </strong><em>How have my connections accumulated over time?</em></p><p>The following charts answer the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tmw_zbDKBhl9S1A6rIU-Hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCiKxZMnnBpuJ8I6DQrMhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bu40ggGOWq889qYv6O-yjA.png" /></figure><p>The three visualizations collectively illustrate the growth of cumulative connections over time, starting from July 2021 through early 2025. The first line chart provides a clear trajectory of how the number of connections evolved monthly, showing a slow initial growth phase until late 2022, followed by a sharp upward trend peaking around mid-2023. After this rapid increase, the growth tapers off and plateaus from late 2023 onward, indicating a saturation or stabilization phase in connection accumulation. This chart effectively communicates the phases of growth: initial inertia, rapid acceleration, and eventual leveling.</p><p>The second chart — a stacked area graph — reinforces this interpretation by visually emphasizing the overall volume and pace of growth. The widening of the green area between late 2022 and mid-2023 highlights the dramatic surge in connections during that period, with the curve flattening afterward. The third chart adds more analytical depth by introducing a 3-month rolling average, smoothing short-term fluctuations and clearly confirming the trend observed earlier. The rolling average closely follows the original line but with less noise, making it easier to see sustained momentum and eventual deceleration. Altogether, these visuals suggest a growth cycle that reached its maturity by early 2024, with the most significant activity concentrated in a roughly six-month window during 2023.</p><p><strong>Question 6:</strong> <em>How senior are the people in my network? What is the seniority demographics of my connections?</em></p><p>This pie chart answers that question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Np619wFzZX5RcWA-YT7l0Q.png" /></figure><p>This pie chart reveals that the majority of my connections fall within the <strong>Intermediate</strong> category, making up <strong>58.4%</strong> of the total. This suggests a strong network concentration around mid-level professionals. Following this, <strong>Managerial</strong> and <strong>Executive</strong> levels represent <strong>18.3%</strong> and <strong>14.5%</strong> respectively, showing a significant presence of decision-makers and leaders within my network as well.</p><p>Meanwhile, <strong>Entry-Level</strong> and <strong>Unknown</strong> categories account for smaller shares, at <strong>5.0%</strong> and <strong>3.7%</strong> respectively. The low proportion of entry-level connections indicate a focus on more experienced professionals or possibly less outreach to newer industry entrants.</p><p>Overall, the distribution implies that my network is skewed towards professionals with substantial career experience.</p><h4>Project Takeaways</h4><ul><li><strong>Peak Networking Period Identified</strong>: The most active connection period was from <strong>late 2022 to mid-2023</strong>, with a sharp peak in <strong>March 2023</strong>, during which I made <strong>170 connections</strong>. This concentrated burst of activity significantly impacted my overall network size.</li><li><strong>Strong Presence in Mid-Level Roles</strong>: Over <strong>58%</strong> of my connections hold <strong>intermediate positions</strong>, indicating that my network is rich in mid-career professionals, with a healthy mix of managerial and executive contacts as well.</li><li><strong>Company Concentration Noted</strong>: The most common company listed by my connections is <strong>Microsoft</strong>, followed by other major organizations such as <strong>Amazon</strong>, <strong>MTN Nigeria</strong>, <strong>CDI</strong>, <strong>CDW</strong>, and <strong>Infosys</strong>.</li><li><strong>Connection Streaks Observed</strong>: Connections occurred on only <strong>298 distinct days</strong>, but notable streaks included one lasting <strong>24 consecutive days</strong>, during which I made over <strong>160 connections</strong>, showing bursts of focused outreach.</li><li><strong>Dominance of Technical Roles</strong>: The most common job title in my network is <strong>Software Engineer</strong>, with <strong>66 connections</strong>, followed by <strong>Senior Software Engineer</strong> at <strong>24 connections</strong> — reflecting a tech-heavy professional circle.</li></ul><p>Find my Jupyter Notebook for the project on <a href="https://github.com/dennis-22-csc/machine_learning/blob/master/notebooks/linkedin/linkedin.ipynb">Github</a></p><p><strong>If this post teaches you one or two things, please take a second to hit the 👋 clap button and leave a comment with your thoughts! ❤️</strong></p><p>Hey, I am Dennis Koko and I would be so glad to connect with you on <a href="https://www.linkedin.com/in/denniskoko/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f8c4f34c54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Short: When Premier League Players Are Going Short and Making a Splash]]></title>
            <link>https://medium.com/@denniskoko/going-short-when-premier-league-players-are-going-short-and-making-a-splash-1051f121c9a6?source=rss-1405a7d766bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1051f121c9a6</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[football-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[football]]></category>
            <dc:creator><![CDATA[Akpotaire Dennis Koko ]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 20:56:32 GMT</pubDate>
            <atom:updated>2025-04-09T15:23:18.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vHdYVR__DaeUtApO" /><figcaption>Image source: <a href="https://www.goal.com/">Goal.com</a></figcaption></figure><p>Are players who attempt more long distance shots more valuable to their teams than those who rely on short distance shots, based on measurable performance metrics such as Expected Goals (xG)?</p><p>The data suggests otherwise.</p><p>Comparing English Premier League data from the 2015/2016 season to the current 2024/2025 shows that the best players (players with the highest npxGs — non penalty expected goals) are taking their shots from short distances.</p><h4>Obtaining Data</h4><p>To study the stability of shots, we scraped shooting data from <a href="https://fbref.com/">https://fbref.com</a> from the 2015/2016 season to the current 2024/2025 season. Starting from the 2015/2016 season is largely an arbitrary choice. This data was saved to a CSV file and loaded into a pandas DataFrame for exploratory and statistical analysis.</p><h4>Exploring Data</h4><p>Our dataset consists of 5655 rows and 27 columns.</p><p>The columns are as follows:</p><ol><li>Rk — Rank<br>This is a count of the rows from top to bottom.</li><li>Player — Name of player.</li><li>Nation — Nationality of the player.</li><li>Pos — Position<br>Position most commonly played by the player</li><li>Squad — Club</li><li>Age — Age at season start</li><li>Born — Year of birth</li><li>90s — 90s Played<br>90s played<br>Minutes played divided by 90</li><li>Gls — Goals<br>Goals scored or allowed</li><li>Sh — Shots Total<br>Shots Total<br>Does not include penalty kicks</li><li>SoT — Shots on Target<br>Shots on Target<br>Note: Shots on target do not include penalty kicks</li><li>SoT% — Shots on Target %<br>Percentage of shots that are on target</li><li>Sh/90 — Shots Total/90<br>Shots total per 90 minutes</li><li>SoT/90 — Shots on target/90<br>Shots on target per 90 minutes</li><li>G/Sh — Goals/Shot<br>Goals per shot</li><li>G/SoT — Goals/Shot on Target<br>Goals per shot on target</li><li>Dist — Average Shot Distance<br>Average distance, in yards, from goal of all shots taken</li><li>PK — Penalty Kicks Made<br>Penalty Kicks Made</li><li>PKatt — Penalty Kicks Attempted<br>Penalty Kicks Attempted</li><li>Matches — matches the stats are associated with</li><li>season — season the stats are associated with</li><li>FK — Shots from Free Kicks<br>Shots from Free Kicks</li><li>xG — xG: Expected Goals<br>Expected Goals<br>xG totals include penalty kicks, but do not include penalty shootouts (unless otherwise noted).</li><li>npxG — npxG: Non-Penalty xG<br>Non-Penalty Expected Goals</li><li>npxG/Sh — npxG/Shot<br>Non-Penalty Expected Goals per shot</li><li>G-xG — Goals — xG<br>Goals minus Expected Goals</li><li>np:G-xG — Non-Penalty Goals — npxG<br>Non-Penalty Goals minus Non-Penalty Expected Goals</li></ol><p>In the dataset, while there are 5655 entries for players spanning different seasons, there are only 1892 number of players in consideration.</p><h4>Filtering Data</h4><p>Since we are most interested in shots data and the expected goals data, we filtered the dataset of missing values by dropping rows with missing values. We can’t input a number such as zero into the columns because that would mean zero shots were attempted by that specific player.</p><h4>Feature Engineering</h4><p>We created a new shot_length column which categorizes shot distance data into short and long. <br>Long distance shots are shots exceeding or equal to 18 yards while short distance shots are those less than 18 yards.</p><h4>Summarizing Data</h4><p>When we examined statistical summaries for the shot distance data, we uncovered the following:<br>1. There are 3581 shooting distance data spanning nine seasons. <br>2. On average, players shot 17 yards. <br>3. The maximum distance shot in the nine seasons is 56.1 yards. <br>4. The lowest distance shot in the nine seasons is 0.9 yards? <br>Who shot the 56.1 yards? Did more than two players shoot 56.1 yards? <br>Who shot 0.9 yards? Did more than two players shoot 0.9 yards?<br>Our analysis uncovered that Kasper Schmeichel shot 56.1 yards while Ragnar Klavan shot 0.9 yards. No other players share this stat with the two.<br>5. A quarter of shots were taken from 13.4 yards or less. Half of the shots in the nine seasons were taken from 17.1 yards or less. <br>Three quarters of the shots were taken from 21 yards or less.</p><h4>Detecting Outliers</h4><p>We used the 1.5 * IQR rule to detect outliers in the distance column. <br>The identified outliers have shooting distances that are either exceptionally long-range (≥32.5 yards) or very close-range (≤1.5 yards).<br>Extremely long-range shots (e.g., Kasper Schmeichel at 56.1 yards, Jorginho at 47.9 yards) often indicate goalkeepers or defensive players attempting shots from their own half.<br>Extremely short-range shots (e.g., Takehiro Tomiyasu at 1.2 yards, Tim Ream at 1.3 yards) typically occur in goalmouth situations, possibly tap-ins or rebounds.</p><h4>Summarizing short distance shots</h4><p>When we examined statistical summaries for the shot distance data for short distance shots, we uncovered the following:<br>1. There are 2023 short distance data spanning nine seasons. <br>2. On average, players shot 13 yards. <br>3. The maximum short distance shot in the nine seasons is 17.9 yards. <br>4. The lowest short distance shot in the nine seasons is 0.9 yards? <br>Who shot the 17.9 yards? Did more than two players shoot 17.9 yards? <br>Our analysis uncovered that 23 players shot 17.9 yards. <br>5. A quarter of short distance shots were taken from 11.4 yards or less. Half of the short distance shots in the nine seasons were taken from 13.9 yards or less. <br>Three quarters of the shots were taken from 16 yards or less.</p><h4>Summarizing long distance shots</h4><p>When we examined statistical summaries for the shot distance data for long distance shots, we uncovered the following:<br>1. There are 1558 short distance data spanning nine seasons representing blablabla percent of the total shot data. <br>2. On average, players shot 22.3 yards. <br>3. The maximum long distance shot in the nine seasons is 56.1 yards. <br>4. The lowest short distance shot in the nine seasons is 18 yards? <br>Who shot the 18 yards? Did more than two players shoot 18 yards? <br>Our analysis uncovered that 23 players shot 18 yards. <br>5. A quarter of long distance shots were taken from 19.7 yards or less. Half of the long distance shots in the nine seasons were taken from 21.6 yards or less. <br>Three quarters of the shots were taken from 24.2 yards or less.</p><h4>Plotting Data</h4><p>We plotted histograms and box plots of shooting distance data. <br>The distribution of shooting distance data appeared to be roughly normal, with a peak around 15–20 yards and a slight skew towards longer distances.<br>We plotted individual histograms for long and short distance shots. <br>The distribution of short distance shots is positively skewed (right-skewed), meaning that as distance increases, the frequency of shots also increases.<br>On the other hand, The distribution of long distance shots is negatively skewed (left-skewed), meaning the frequency of shots decreases as distance increases.</p><p>In the box plots, the distribution of “long” shots is more spread out, suggesting greater variation in shot selection from distance.<br>There were extreme long-distance shots, which could indicate rare attempts from very far. Short shots were more clustered, meaning they are generally taken from more predictable distances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSFLDPvC_kYe-Xvv2L_4Ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRF0PSm4eeIXTZYEzd3N8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWdNsd5y2lfcNQvjTLpKyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F6nsIS4imCbJH7prBN7IA.png" /></figure><h4>Determining Season by Season stability of shot quality per attempt</h4><p>To analyze how consistently players generate quality chances (measured by Expected Goals, or xG) relative to how often they shoot, grouped by shot type (long or short) and season, we grouped the dataset by player, season, and shot length (short vs long) to compute:</p><ol><li>Total number of shots (Sh)</li><li>Total non-penalty expected goals (Expected_npxG)</li></ol><p>Then we calculated xg_per_shot. This metric represents the average quality of a shot, based on the expected goal value per attempt.<br>A higher xg_per_shot suggests that the player typically shoots from positions with a higher chance of scoring.<br>A lower value may reflect long-range efforts, poor shot selection, or shots taken under pressure.<br>We filtered the dataset by players with at least 100 shot attempts to focus on more consistent contributors.</p><p><strong>Key observations</strong><br>Players like Erling Haaland, Gabriel Jesus, and Dominic Solanke exhibit both quality and quantity — they consistently take a lot of shots and do so from advantageous positions.<br>Their xG per shot ranges from ~0.16 to 0.20, indicating strong positioning and efficient shot selection.<br>Haaland appears in multiple seasons with similar xG/Shot values, reflecting a consistently high standard in shot quality and offensive output.<br>These players play a central role in their team’s attack. High shot counts (100+) suggest they’re frequently involved in build-up and finishing sequences.<br>The dominance of the “short” shot_length category among top performers further suggests that players who take more shots closer to goal tend to generate higher xG per attempt — underscoring the value of proximity and shot location.</p><h4>Stability Analysis of Long-Range vs. Short-Range Shot Performance</h4><p>In this analysis, we examine whether the performance of long-range shots is less stable than short-range shots season by season. To assess this, we focus on the Expected Goals per Shot (xG per shot) for each player across multiple seasons, differentiating between long and short shots.</p><p><strong>Steps taken to Evaluate Stability:</strong></p><ol><li>Calculate xG per Shot for Each Player in Each Season:<br>For each player, we calculated Expected Goals per Shot (xG per shot) for both short and long-range shots during each season. This is the Expected Non-penalty xG (Expected_npxG) divided by the number of shots taken (Sh) for each shot length (short or long).</li><li>Calculate xG per Shot for the Previous Season:<br>We then computed the xG per shot for the previous season of each player. This allows us to compare the player’s performance in one season with that of the next, giving us insight into any fluctuations in their shooting efficiency.</li><li>Analyze the Correlation Between Current and Previous Season’s xG per Shot:<br>We then assessed the correlation between the current season’s xG per shot and the previous season’s xG per shot. A strong positive correlation would indicate that a player’s shooting performance is consistent from one season to the next, while a weak correlation suggests greater variability. This analysis is particularly useful for distinguishing between long-range and short-range shots, as these may show different levels of stability.</li><li>Generate plots<br>Finally, we generated scatterplots and heatmaps to visualise the correlations.</li></ol><p>The scatterplot visualized the relationship between xg_per_shot and xg_per_shot_last, separately for long and short shots.</p><p><strong>Observations:</strong><br>For long shots, there is a positive trend, but the data is quite scattered, reinforcing the weak correlation seen in the matrix.<br>For short shots, the points are tightly clustered around the trendline, indicating much stronger consistency between current and past xG per shot.<br><strong>Insights:</strong><br>Long shot efficiency varies widely across time, suggesting that external factors — like shot distance, defensive pressure, and game context — may heavily influence outcomes.<br>Short shots tend to yield more stable xG values, reflecting higher predictability in performance.<br>For modeling or decision-making based on prior performance (e.g., scouting, player evaluation), xG from short shots is a more reliable and stable indicator than from long shots.</p><p>The heatmap illustrated the correlation between current xg_per_shot and past xg_per_shot_last for short and long shots.</p><p><strong>Observations:</strong><br>The correlation between long shot xG per shot and its past value is 0.44, indicating a weak-to-moderate relationship.<br>The correlation for short shot xG per shot and its past value is significantly higher at 0.97, suggesting strong stability over time.<br><strong>Insights:</strong><br>Short shots show much stronger consistency in efficiency compared to long shots.<br>Long shot xG is less predictable from previous values, likely due to greater variability influenced by situational factors like distance, angle, or defensive pressure.<br>For predictive modeling or performance evaluation, focusing on short shots offers a more reliable and stable indicator of a player’s finishing ability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xq2ElYX7Yubn_GtPrBeUuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5NPqzqd_4DGHjO1dpv2hQ.png" /></figure><h4>Project Takeaways</h4><ol><li>Mid-range shots (10–25 yards) are the most common, aligning with the optimal shooting distances in football.</li><li>Few extremely short or long shots are attempted, indicating that players tend to take shots from strategic positions.</li><li>Long-distance shots decrease significantly beyond 25 yards, showing that players prioritize efficiency over speculative shooting.</li><li>Short-range shots demonstrate significantly more consistency in xG per shot across seasons compared to long-range efforts, which are more prone to fluctuation.</li><li>Past xG performance on short shots is a much stronger indicator of future outcomes than it is for long shots, making them more reliable for forecasting player efficiency.</li><li>Teams should prioritize optimizing short-range shooting opportunities, as they offer higher-quality, more predictable chances.<br>Long shots, while occasionally effective, should be approached as low-probability, high-variance options — best suited for specific contexts rather than regular strategy.</li></ol><p>Find my Jupyter Notebook for the project on <a href="https://github.com/dennis-22-csc/machine_learning/blob/master/notebooks/epl/epl_analysis.ipynb">Github</a></p><p><strong>If this post teaches you one or two things, please take a second to hit the 👋 clap button and leave a comment with your thoughts! ❤️</strong></p><p>Hey, I am Dennis Koko and you can connect with me on <a href="https://www.linkedin.com/in/denniskoko/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1051f121c9a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Normalization: Fine-Tuning Your Databases For Scalability]]></title>
            <link>https://medium.com/@denniskoko/database-normalization-fine-tuning-your-databases-for-scalability-97a06257473c?source=rss-1405a7d766bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/97a06257473c</guid>
            <category><![CDATA[database-scalability]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-normalization]]></category>
            <category><![CDATA[normalization]]></category>
            <category><![CDATA[database-design]]></category>
            <dc:creator><![CDATA[Akpotaire Dennis Koko ]]></dc:creator>
            <pubDate>Sat, 11 May 2024 11:05:03 GMT</pubDate>
            <atom:updated>2024-05-11T11:54:01.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*bRYU-Xd8Aa_OIeWWy12ySQ.jpeg" /></figure><p>You’ve probably come across the topic of database normalization.</p><p>Having recently come across this topic, here is my attempt to explain it.</p><h3>Database Normalization</h3><p>This is the practice of altering a database schema to eliminate data redundancy and improve data integrity.</p><p><strong>Database Schema: </strong>The structure of your database tables, columns, rows, and the constraints applied to them.</p><p><strong>Data Redundancy: </strong>Redundancy occurs when the same data is stored in multiple places within a database. This can lead to wasted storage space and inconsistencies when data needs to be updated.</p><p><strong>Data Integrity: </strong>Data integrity refers to the accuracy and consistency of data in a database. Normalization helps ensure that data remains accurate by minimizing the possibility of errors or inconsistencies arising from redundancy.</p><h3>Normal forms</h3><p>These are rules that you can run your database tables against to spot opportunities for normalization.</p><p>You will check if your database table satisfies each of the rules, for a rule it doesn’t satisfy, it represents an opportunity to normalize things.</p><p>The rules are in several categories and each category forms part of an hierarchy.</p><p>These normal forms are as follows:</p><ol><li>Ist Normal Form (1NF)</li><li>2nd Normal Form (2NF)</li><li>3rd Normal Form (3NF)</li></ol><p>We will run a couple of database tables against the rules in each category to gain experience normalizing database tables. But before we do that, let’s examine some key concepts.</p><h3>Key Concepts</h3><h4>Candidate keys:</h4><p>Candidate keys are attributes or sets of attributes that uniquely identify each row in a table.</p><p>In a table of Employees for example, EmployeeID might be a candidate key because it uniquely identifies each employee. Only one ID is associated with a particular employee. No two employees share the same ID.</p><p>Another attribute that can be used to uniquely identify a particular employee is their email address. No two employees share the same email address.</p><p>A candidate key can consist of one or more attributes from the table.</p><p>For example, in the table representing Employees, while a candidate key could be a single attribute like EmployeeID, which uniquely identifies each employee, a candidate key could also be a combination of attributes, such as (FirstName, LastName), which together uniquely identify each employee. This is usually necessary if one of the attributes cannot uniquely identify the employee.</p><p>So, when we say candidate keys are a “set of attributes,” it signifies that they can be composed of one or more columns from the table, and these columns, when taken together, have the property of uniquely identifying each row in the table.</p><p>Note, there can be multiple candidate keys in the table, that is, there can be multiple attributes that can individually be considered as candidate keys, each uniquely identifying rows in the table. For example, if EmployeeID and Email are attributes in the Employees table, since individually they uniquely identify rows in the table, each are candidate keys.</p><p>But this should not be confused with the situation where a candidate key is a set of attributes in the table. In this case, each of the attributes cannot on their own be considered a candidate key.</p><p>Simply because each cant on their own uniquely identify rows in the table.</p><p>Candidate keys are also minimal superkeys, meaning no proper subset of a candidate key can also uniquely identify rows.</p><p>Let’s assume the ID of the first employee in a table is EMP101 and the ID of the second employee is EMP102, we can see that if we divide the ID into two parts — the letter part and the number part — the letter part fails to uniquely identify a particular employee.</p><p>This means EmployeeID as a candidate key is minimal since a proper subset of it — the letter part — cannot uniquely identify a particular employee.</p><p>This should also hold true if two attributes are combined to form a candidate key. It must be so that one of the attributes cannot uniquely identify a particular employee. If both can uniquely identify a particular employee, then it doesn’t make sense combining them to form one single candidate key.</p><h4>Non-prime attributes:</h4><p>Non-prime attributes are attributes in a table that are not part of the candidate key.</p><p>In other words, they are not a part of the minimal set of attributes that can be used to uniquely identify each row in the table.</p><p>For example, in the table of Employees where the candidate key is EmployeeID, non-prime attributes would include attributes like Name, Department, and Salary. These attributes are not part of the candidate key and are dependent on it for their values. We can use the candidate key to look them up.</p><p>In a table of Employees containing such columns as FirstName, LastName, Department, Salary and the FirstName and LastName columns together form the candidate key, non-prime attributes will include Department and Salary.</p><h4>Primary Key:</h4><p>This is the key from a bunch of candidate keys that you’ve chosen to be using all the time to look up rows in the database.</p><p>In a table of Employees where there are two candidate keys (EmployeeID, Email), whichever of them you pick to be the main way to identify each row is the primary key.</p><h4>Composite Primary Key:</h4><p>A primary key can be a combination of attributes. When a primary key consists of more than one attribute, it’s called a composite primary key. This is usually when the candidate key is a combination of attributes.</p><p>For instance, in a table of Employees, a single attribute like “Employee ID” might not be enough to uniquely identify each employee because there could be employees with the same ID (for example, if the organization uses different ID systems for different departments). In such cases, you might need a combination of attributes to uniquely identify each employee. For example, a combination of “Employee ID” and “Department ID” could serve as a composite primary key, ensuring that each employee is uniquely identified within the context of their department.</p><h4>Functional dependency:</h4><p>Functional dependency is a relationship between two attributes in a table, where the value of one attribute uniquely determines the value of another attribute.</p><p>In the employee table, if we have a functional dependency EmployeeID → Name, it means that for every EmployeeID, there is only one corresponding Name associated with it. Similarly, if we have a functional dependency Department → Manager, it implies that for each department, there is only one manager.</p><p>Imagine you have a table that stores information about employees in a company. Each employee has a unique identifier called EmployeeID. Now, besides EmployeeID, you also have their Name, Department, and Salary. EmployeeID is a prime attribute because it uniquely identifies each employee. However, Name, Department, and Salary are not prime attributes because they don’t uniquely identify employees. Multiple employees could have the same name, work in the same department, or have the same salary.</p><p>Candidate keys in this context act as special keys that uniquely identify employees without any ambiguity. EmployeeID serves as a candidate key because it can lead us directly to a specific employee’s details. But let’s say each employee also has a unique email address. In that case, EmployeeID and Email could both be candidate keys because either one could help us find an employee’s information without any confusion.</p><p>Now, let’s talk about functional dependency. Suppose we have a functional dependency between EmployeeID and Name. It means if you know an employee’s ID, you can find out their name. So, EmployeeID → Name. Similarly, if you know an employee’s Department, you can find out their Salary. So, Department → Salary. These dependencies help establish relationships between attributes in the table, allowing us to infer certain information based on what we already know.</p><p>Database normalization aims to minimize redundancy and dependency issues in a database schema by organizing attributes into relations such that they satisfy certain normal forms. Non-prime attributes, candidate keys, primary keys, composite primary keys, and functional dependencies are important concepts in this process.</p><p>Next, we will explore the various normal forms.</p><h4>1st Normal Form (1NF)</h4><p><strong>Rule:</strong></p><p>A single cell in a table must not contain multiple values. Or even composite values that can be treated individually.</p><p>For example, a phone number cell for any employee must not contain multiple phone numbers.</p><p>An address cell for any employee must not contain composite values such as street address, city, state, zip code.</p><p>If a table contains composite or multi-valued attributes, it violates the First Normal Form.</p><p>When a table is run against this rule and it turns out to violate it, the table should be modified such that a second row is created to contain the second phone number or for the case of composite values, additional columns are created for each part of the composite value. This means there will be a street column, there will be a city column, there will be a state column, there will be a zip code column.</p><h4>2nd Normal Form (2NF)</h4><p>This test should only be done after the first test has been done.</p><p><strong>Rule:</strong></p><p>A table should not contain partial dependency.</p><p>This means that in a situation where there are multiple candidate keys or there is a composite primary key, any non-prime attribute in the table must not depend on only one of the candidate keys or only a part of the composite primary key.</p><p>For example, if DepartmentID and EmployeeID are to be jointly used to look up rows in a table, it should not be possible to look up a particular row in that table using one of the IDs alone.</p><p>If one of the IDs can be used to look up any row, the table should be split so this is no longer the case.</p><h4>3rd Normal Form (3NF)</h4><p>This test should only be done after the second test has been done.</p><p><strong>Rule:</strong></p><p>There should not be transitive dependency for non-prime attributes.</p><p>A transitive dependency occurs when a non-prime attribute (attribute not part of the primary key) is dependent on another non-prime attribute, which in turn is dependent on the primary key. This creates a chain of dependencies that can lead to data redundancy and inconsistencies.</p><p>We will get to understand all of these better when we examine a couple of database scenarios which we will be doing next.</p><p><strong>Scenario 1:</strong> Storing Order information where each order can have multiple products</p><pre>| Order id | Item              | Price  |<br>| - - - -  | - - - - - - - - - | - - - -|<br>| 1        | milk, milo        | 5, 7   |<br>| 2        | sugar, cornflakes | 8, 150 |<br>| 3        | cream, spray      | 6, 500 |</pre><p>The above is a database table already containing data.</p><p>This table needs to be run against the rules of 1NF which says that a single cell in a table must not contain multiple values. Or even composite values that can be treated individually.</p><p>Does this table satisfy 1NF?</p><p>No.</p><p>What you should observe about the table is that in the <em>Item</em> column, there are multiple items per row.</p><p>Therefore, cells in the table contain multiple values.</p><p>What should we do now?</p><p>Alter the table such that it appears as the below:</p><pre>| Order id | Item         | Price  |<br>| - - - - -| - - - - - - -| - - - -|<br>| 1        | milk         | 5      |<br>| 1        | milo         | 7      |<br>| 2        | sugar        | 8      |<br>| 2        | cornflakes   | 150    |<br>| 3        | cream        | 6      |<br>| 3        | spray        | 500    |</pre><p>What we did here is to put each item in its own row.</p><p>Next, we will run the new table against 2NF to see if it satisfies it. 2NF states that a table should not contain partial dependency.</p><p>This means that in a situation where there are multiple candidate keys or there is a composite primary key, any non-prime attribute in the table must not depend on only one of the candidate keys or only a part of the composite primary key.</p><p>What would be the candidate key or keys for the above table?</p><p>There will only be 1 candidate key and the key will be composed of two columns: OrderId and Item. OrderId alone is not enough to uniquely identify a row since multiple items in the same order share the same Id. Item alone is not also enough to uniquely identify a row since the same item will appear in different orders.</p><p>Since the candidate key is composed of two columns and there are no other candidate keys in the table, the primary key will be a composite primary key.</p><p>What are the non-prime attributes of the table?</p><p>There is only 1 non-prime attribute and that is price.</p><p>To satisfy 2NF, non-prime attributes in this case price should not depend on only a part of the composite primary key. This means that if we want to know the price associated with a particular item, we should not be able to use only the order Id alone (a part of the composite primary key) or the item alone (a part of the composite primary key).</p><p>For the given table, can we uniquely look up the price associated with the item milo using the order Id 1?</p><p>No. using order Id 1 will return two prices since there are two items associated with the order Id 1.</p><p>Can we alternatively uniquely look up the price associated with the item milo using the name milo alone?</p><p>While it looks like we can, what happens when in a new order, the item milo is ordered for and added to the table? This means the name milo will be appearing twice. If we look up a price using the name milo, we will get two prices instead of 1.</p><p>What is the conclusion from all of these?</p><p>The conclusion is that the table satisfies 2NF since we can’t look up any of the non-prime attributes using a part of the composite primary key.</p><p>What is 3NF and does the table meet it?</p><p>3NF states that there should not be transitive dependency for non-prime attributes.</p><p>This means that in a table, a non-primary attribute should not be uniquely identified by another non-primary attribute when the second non-primary attribute is being looked up using the primary attribute. Instead, all non-primary attributes should directly connect to the primary key.</p><p>This rule cannot be applied to the table since there is only 1 non-prime attribute which is price.</p><p>The table needs to have at least two non-prime attributes before this rule can be evoked.</p><p><strong>Scenario 2:</strong> In the table, customer information exists alongside order information</p><pre>| Order id | Item              | Price  | Customer Name  | Customer Email       | Customer Address     |<br>| - - - - -| - - - - - - - - - | - - - -| - - - - - - - -| - - - - - - - - - - -| - - - - - - - - - - -|<br>| 1        | Milk, Milo        | 5, 7   | John Smith     | john@example.com     | 123 Main St, City    |<br>| 2        | Sugar, Cornflakes | 8, 150 | Emily Johnson  | emily@example.com    | 456 Elm St, Town     |<br>| 3        | Cream, Spray      | 6, 500 | Michael Brown  | michael@example.com  | 789 Oak St, Village  |</pre><p>We will start by checking if the table meets 1NF.</p><p>It doesn’t, so we will refactor it to the below:</p><pre>| Order id | Item       | Price | Customer Name | Customer Email      | Customer Address |<br>| - - - - -| - - - - - -| - - - | - - - - - - - | - - - - - - - - - - | - - - - - - - - - - -|<br>| 1        | Milk       | 5     | John Smith    | john@example.com    | 123 Main St, City |<br>| 1        | Milo       | 7     | John Smith    | john@example.com    | 123 Main St, City |<br>| 2        | Sugar      | 8     | Emily Johnson | emily@example.com   | 456 Elm St, Town |<br>| 2        | Cornflakes | 150   | Emily Johnson | emily@example.com   | 456 Elm St, Town |<br>| 3        | Cream      | 6     | Michael Brown | michael@example.com | 789 Oak St, Village|<br>| 3        | Spray      | 500   | Michael Brown | michael@example.com | 789 Oak St, Village|</pre><p>Does the table meet 2NF?</p><p>To satisfy 2NF, non-prime attributes in this case price, customer name, customer email, and customer address should not depend on only a part of the composite primary key.</p><p>Because we can look up attributes such as customer name, customer email, customer address using the order id alone, the table doesn’t satisfy 2nf.</p><p>To make the table satisfy 2nf, we will need to divide the table such that order id will stand alone as a primary key.</p><p>Table 1: Orders</p><pre>| Order ID | Customer Name | Customer Email      | Customer Address    |<br>| - - - - -| - - - - - - - | - - - - - - - - - - | - - - - - - - - - - |<br>| 1        | John Smith    | john@example.com    | 123 Main St, City   |<br>| 2        | Emily Johnson | emily@example.com   | 456 Elm St, Town    |<br>| 3        | Michael Brown | michael@example.com | 789 Oak St, Village |</pre><p>Table 2: Order Items</p><pre>| Order ID | Item       | Price |<br>| - - - - -| - - - - - -| - - - |<br>| 1        | Milk       | 5     |<br>| 1        | Milo       | 7     |<br>| 2        | Sugar      | 8     |<br>| 2        | Cornflakes | 150   |<br>| 3        | Cream      | 6     |<br>| 3        | Spray      | 500   |</pre><p>Two tables have been created, order table and order items table.</p><p>Next, we will run both tables against 2nf.</p><p>2nf does not apply to the orders table since the primary key is not composite and there can only be one candidate key in the orders table — order id.</p><p>How about the order items table?</p><p>A composite primary key will be used to look up items in the table.</p><p>The table also meets 2f since you can’t reliably find the price of a given item without knowing both the order id and the item name.</p><p>Does the orders table meet 3nf?</p><p>3NF states that there should not be transitive dependency for non-prime attributes.</p><p>This means that in a table, it should not be possible to use a non-primary attribute to uniquely identify another non-primary attribute that cannot be uniquely identified using the primary attribute. Instead, all non-primary attributes should only be uniquely identified using the primary attribute.</p><p>Customer Email is a non prime attribute, while because of the data currently in the table, it looks like it can be used to uniquely identify rows in the table, what happens when the same customer makes a new order?</p><p>This means that there will be a new order id with the same customer information as an existing order id.</p><p>Order id is therefore the only attribute we can use to uniquely identify rows in the orders table.</p><p>The table therefore satisfies 3nf.</p><p>But if we want to plan for the future, it will be better we further normalize the tables to have a separate customer table where a customer email is the primary key. There will now be a reference to the customer email in the order table.</p><p>Table 1: Customers</p><pre>| Customer Email      | Customer Name | Customer Address    |<br>| - - - - - - - - - - | - - - - - - - | - - - - - - - - - - |<br>| john@example.com    | John Smith    | 123 Main St, City   |<br>| emily@example.com   | Emily Johnson | 456 Elm St, Town    |<br>| michael@example.com | Michael Brown | 789 Oak St, Village |</pre><p>Table 2: Orders</p><pre>| Order ID | Customer Email      |<br>| - - - - -| - - - - - - - -     |<br>| 1        | john@example.com    |<br>| 2        | emily@example.com   |<br>| 3        | michael@example.com |</pre><p>Table 3: Order Items</p><pre>| Order ID | Item       | Price |<br>| - - - - -| - - - - - -| - - - |<br>| 1        | Milk       | 5     |<br>| 1        | Milo       | 7     |<br>| 2        | Sugar      | 8     |<br>| 2        | Cornflakes | 150   |<br>| 3        | Cream      | 6     |<br>| 3        | Spray      | 500   |</pre><p><strong>Scenario 3</strong>: Storing information pertaining to multiple entities in one table</p><pre>| StudentID | Student Name  | Course Name | Course Score | Department Name | Department Director | Director Phone Number |<br>| - - - - - | - - - - - - - | - - - - - - | - - - - - - -| - - - - - - - - | - - - - - - - - - - | - - - - - - - - - - - |<br>| 1         | Alice Smith   | Mathematics | 95           | Math            | Dr. Johnson         | 123–456–7890          |<br>| 1         | Alice Smith   | Physics     | 88           | Physics         | Prof. Martinez      | 234–567–8901          |<br>| 1         | Alice Smith   | Chemistry   | 91           | Chemistry       | Dr. Thompson        | 345–678–9012          |<br>| 2         | Bob Johnson   | English     | 85           | English         | Prof. Rambo         | 214–567–8101          |<br>| 2         | Bob Johnson   | Art History | 80           | Arts            | Dr. Lee             | 456–789–0123          |<br>| 2         | Bob Johnson   | Psychology  | 87           | Psychology      | Dr. Taylor          | 567–890–1234          |<br>| 3         | Charlie Brown | History     | 75           | History         | Dr. Adams           | 345–678–9012          |<br>| 3         | Charlie Brown | Literature  | 82           | Literature      | Prof. Carter        | 678–901–2345          |<br>| 3         | Charlie Brown | Economics   | 79           | Economics       | Dr. White           | 789–012–3456          |</pre><p>The above table meets 1NF but does it meet 2NF?</p><p>Before we answer that question, we need to determine the key used to access data in the table.</p><p>The composite key of StudentID and CourseName is used to access data in the table.</p><p>Could any non primary attribute in the table be accessed using just a part of this composite primary key?</p><p>Yes.</p><p>Student names can be accessed using studentIDs alone.</p><p>Course information can be accessed using CourseIds alone.</p><p>Department directors can be accessed using Department names alone.</p><p>The table will therefore need to be refactored to the below:</p><p>Table 1: Students</p><pre>| StudentID | Student Name |<br>| - - - - - | - - - - - - |<br>| 1         | Alice Smith |<br>| 2         | Bob Johnson |<br>| 3         | Charlie Brown|</pre><p>Table 2: Courses</p><pre>| Course ID| Course Name | Department ID|<br>| - - - - -| - - - - - - | - - - - - -  |<br>| 1        | Mathematics | 1            |<br>| 2        | Physics     | 2            |<br>| 3        | Chemistry   | 3            |<br>| 4        | English     | 4            |<br>| 5        | Art History | 5            |<br>| 6        | Psychology  | 6            |<br>| 7        | History     | 7            |<br>| 8        | Literature  | 8            |<br>| 9        | Economics   | 9            |<br></pre><p>Table 3: Grades</p><pre>| Course ID | Course Score | StudentID |<br>| - - - - - | - - - -  - - | - - - - - |<br>| 1         | 95           | 1         |<br>| 2         | 88           | 1         |<br>| 3         | 91           | 1         |<br>| 4         | 85           | 2         |<br>| 5         | 80           | 2         |<br>| 6         | 87           | 2         |<br>| 7         | 75           | 3         |<br>| 8         | 82           | 3         |<br>| 9         | 79           | 3         |</pre><p>Table 4: Department</p><pre>| DepartmentID | Department Name | DirectorID |<br>| - - - - - - -| - - - - - - - - | - - - - - - |<br>| 1            | Math            | 1           |<br>| 2            | Physics         | 2           |<br>| 3            | Chemistry       | 3           |<br>| 4            | English         | 4           |<br>| 5            | Arts            | 5           |<br>| 6            | Psychology      | 6           |<br>| 7            | History         | 7           |<br>| 8            | Literature      | 8           |<br>| 9            | Economics       | 9           |</pre><p>Table 5: Director</p><pre>| DirectorID | Director Name | Director Phone Number |<br>| - - - - - - | - - - - - - - -| - - - - - - - - - - - -|<br>| 1           | Dr. Johnson    | 123–456–7890           |<br>| 2           | Prof. Martinez | 234–567–8901           |<br>| 3           | Dr. Thompson   | 345–678–9012           |<br>| 4           | Prof. Martinez | 234–567–8901           |<br>| 5           | Dr. Lee        | 456–789–0123           |<br>| 6           | Dr. Taylor     | 567–890–1234           |<br>| 7           | Dr. Adams      | 345–678–9012           |<br>| 8           | Prof. Carter   | 678–901–2345           |<br>| 9           | Dr. White      | 789–012–3456           |</pre><p>You’ve seen database normalization in action. How do you do all of these in the wild using a real database setup?</p><p>Watch out for my next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97a06257473c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Content Negotiation in FASTAPI]]></title>
            <link>https://medium.com/@denniskoko/implementing-content-negotiation-in-fastapi-371d03c59c02?source=rss-1405a7d766bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/371d03c59c02</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[content-negotiation]]></category>
            <dc:creator><![CDATA[Akpotaire Dennis Koko ]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 21:39:15 GMT</pubDate>
            <atom:updated>2024-04-22T07:27:59.841Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve been introduced to the concept of content negotiation in <a href="https://medium.com/@dennisthebusinessguru/content-negotiation-the-art-and-science-of-giving-clients-of-your-api-the-data-they-want-in-the-aa58e4eb1661">this article</a>.</p><p>As a FASTAPI developer, how do you implement it?</p><p>Below is a program that shows you how to implement it:</p><pre>from fastapi import FastAPI, Request, Response, Query<br>from fastapi.responses import JSONResponse, HTMLResponse<br>from typing import Optional<br><br>app = FastAPI()<br><br># Sample data<br>data = {<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;email&quot;: &quot;john.doe@example.com&quot;<br>}<br><br># Define function to generate HTML content from data<br>def generate_html(data):<br>    html_content = &quot;&quot;&quot;<br>    &lt;!DOCTYPE html&gt;<br>    &lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>        &lt;title&gt;User Info&lt;/title&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;h1&gt;User Info&lt;/h1&gt;<br>        &lt;ul&gt;<br>            &lt;li&gt;Name: {name}&lt;/li&gt;<br>            &lt;li&gt;Age: {age}&lt;/li&gt;<br>            &lt;li&gt;Email: {email}&lt;/li&gt;<br>        &lt;/ul&gt;<br>    &lt;/body&gt;<br>    &lt;/html&gt;<br>    &quot;&quot;&quot;.format(**data)<br>    return html_content<br><br># Define function to generate XML content from data<br>def generate_xml(data):<br>    xml_content = f&quot;&lt;user&gt;\n&quot;<br>    for key, value in data.items():<br>        xml_content += f&quot;    &lt;{key}&gt;{value}&lt;/{key}&gt;\n&quot;<br>    xml_content += &quot;&lt;/user&gt;&quot;<br>    return xml_content<br><br># Define endpoint to handle content negotiation for Accept and query<br>@app.get(&quot;/user&quot;)<br>async def get_user(request: Request, format: Optional[str] = Query(None, pattern=&quot;^(json|html|xml)$&quot;)):<br>    # Check if query parameter is present<br>    if format:<br>        if format == &quot;json&quot;:<br>            return JSONResponse(content=data)<br>        elif format == &quot;html&quot;:<br>            return HTMLResponse(content=generate_html(data))<br>        elif format == &quot;xml&quot;:<br>            return Response(content=generate_xml(data), media_type=&quot;application/xml&quot;)<br><br>    # Check client&#39;s preferred content type from Accept header<br>    accept_header = request.headers.get(&quot;Accept&quot;)<br>    <br>    # Default to JSON if Accept header is not provided<br>    if not accept_header:<br>        return JSONResponse(content=data)<br>    <br>    # Parse Accept header to determine client&#39;s preferred content type<br>    if &quot;application/json&quot; in accept_header:<br>        return JSONResponse(content=data)<br>    elif &quot;text/html&quot; in accept_header:<br>        return HTMLResponse(content=generate_html(data)<br>)<br>    elif &quot;application/xml&quot; in accept_header:<br>        return Response(content=generate_xml(data), media_type=&quot;application/xml&quot;)<br>    else:<br>        # If no matching content type is found, return a 406 Not Acceptable response<br>        return Response(status_code=406, content=&quot;406 Not Acceptable: Unsupported Media Type&quot;)<br><br># Define endpoint to handle content negotiation for file extension<br>@app.get(&quot;/user.{format}&quot;)<br>async def get_user_by_extension(format: str):<br>    if format == &quot;json&quot;:<br>        return JSONResponse(content=data)<br>    elif format == &quot;html&quot;:<br>        return HTMLResponse(content=generate_html(data))<br>    elif format == &quot;xml&quot;:<br>        return Response(content=generate_xml(data), media_type=&quot;application/xml&quot;)<br>    else:<br>        raise HTTPException(status_code=406, detail=&quot;Unsupported Media Type&quot;)<br><br># Run the application<br>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)<br><br></pre><p>The above program can be put in a file <em>content_negotiation.py</em> and run using the bash command:</p><pre>python3 content_negotiation.py</pre><p>Output on my Ubuntu System:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7k3ADyBrvo_S4o8XHwmnoQ.png" /></figure><p>As you can see in the screenshot, a new shell session has been opened from where I will be running the curl commands to test the endpoint.</p><p>Test 1: Checking to see if specifying xml in the Accept header will return an xml response using the below curl command:</p><pre>curl -H &quot;Accept: application/xml&quot; http://localhost:8000/user</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJy_uZS4cTrkcmrQE5h_YQ.png" /></figure><p>Test 2: Checking to see if specifying html in the Accept header will return a html response using the below curl command:</p><pre>curl -H &quot;Accept: text/html&quot; http://localhost:8000/user</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUIQY80lnSgnDyFEFg0TNQ.png" /></figure><p>Test 3: Checking to see if specifying json in the Accept header will return a json response using the below curl command:</p><pre>curl -H &quot;Accept: application/json&quot; http://localhost:8000/user</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oaGOt3ch_iIeBym-pRUmIQ.png" /></figure><p>Test 4: Checking to see if specifying zip in the Accept header will return an error using the below curl command:</p><pre>curl -H &quot;Accept: application/zip&quot; http://localhost:8000/user</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPOJdQbZi__TZVmPNUI3dg.png" /></figure><p>Test 5: Checking to see if not including the Accept header will return an error using the below curl command:</p><pre>curl http://localhost:8000/user</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Iy3LS9cSmBuJF6CQR0TFA.png" /></figure><p>The error being returned does not reveal what the issue is, the code will therefore need some modification.</p><h4>Testing Query Parameter</h4><p>Test 1: Checking to see if specifying xml as the value of format will return an xml response using the below curl command:</p><pre>curl http://localhost:8000/user?format=xml</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eInzEWP0do6_iE8-CVeD4w.png" /></figure><p>Test 2: Checking to see if specifying html as the value of format will return an html response using the below curl command:</p><pre>curl http://localhost:8000/user?format=html</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1anLVSbQqPThcN4IaLOxA.png" /></figure><p>Test 3: Checking to see if specifying json as the value of format will return a json response using the below curl command:</p><pre>curl http://localhost:8000/user?format=json</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWSD2S6BkRia_vCe-8L1lg.png" /></figure><h4>Testing File Extension</h4><p>Test 1: Checking to see if adding xml as an extension to user will return an xml response using the below curl command:</p><pre>curl http://localhost:8000/user.xml</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAQnr0mIPHYXsPU_oZPg0g.png" /></figure><p>Test 2: Checking to see if adding html as an extension to user will return an html response using the below curl command:</p><pre>curl http://localhost:8000/user.html</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5kJ_m95XgGNUNDALn5eVA.png" /></figure><p>Test 3: Checking to see if adding json as an extension to user will return a json response using the below curl command:</p><pre>curl http://localhost:8000/user.json</pre><p>Output on my Ubuntu system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHmXnLp1ICxqy3VDMaPD2w.png" /></figure><p>With these, you have seen how content negotiation can be implemented in FASTAPI.</p><p>Thanks for reading this article!</p><p>Please leave a comment in the below box if you have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=371d03c59c02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Content Negotiation: The Art and Science of Giving Clients of Your API the Data They Want, in the…]]></title>
            <link>https://medium.com/@denniskoko/content-negotiation-the-art-and-science-of-giving-clients-of-your-api-the-data-they-want-in-the-aa58e4eb1661?source=rss-1405a7d766bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa58e4eb1661</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[content-negotiation]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Akpotaire Dennis Koko ]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 21:36:02 GMT</pubDate>
            <atom:updated>2024-04-24T03:21:15.778Z</atom:updated>
            <content:encoded><![CDATA[<h3>Content Negotiation: The Art and Science of Giving Clients of Your API the Data They Want, in the Format They Want It</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpng5gmRCzj9Its85s9mAQ.jpeg" /><figcaption>Leonardo AI</figcaption></figure><p>You’re a beginner.</p><p>You haven’t encountered the subject of content negotiation yet.</p><p>You’re building an API.</p><p>You will most probably code the API to return a JSON response, don’t you?</p><p>You probably believe only JSON responses are returned by APIs.</p><p>But are you aware that the data your API returns, some clients will appreciate it in XML? Or plain text?</p><p>Do you know your API can as well return data in HTML?</p><p>Your data is a REST resource and Ruchira Madhushan Rajapaksha in his <a href="https://medium.com/javarevisited/content-negotiation-for-reactive-web-services-in-spring-boot-3-0d8ee13fd5b4">article</a> on content negotiation said that REST resources can have multiple representations including but not limited to HTML, JSON, and XML.</p><p>Each of these representations are formats your data can exist on the server in and be returned to clients in.</p><p>In the HTTP protocol, API clients can specify the format they want your data in, as a back-end engineer, it is good practice for you to code your data to be returned in multiple representations based on client preferences.</p><h3>Content Negotiation</h3><p>In Adegbenga Agoro’s <a href="https://medium.com/@adegbengaagoro/implementing-content-negotiation-in-adonisjs-v5-e84d4fd14868">article</a> on content negotiation, citing MDN, Content Negotiation is the mechanism that is used for serving different representations of a resource to the same URI.</p><p>Content Negotiation, when implemented in your application, enables you to use the same URL or endpoint to serve your data in any of HTML, JSON, XML, plain text, etc., to the clients of your API.</p><p>Let’s imagine your data to be the food being served by a restaurant.</p><p>Typically, diners aren’t allowed to specify whether they want it on a plate, in a bowl, or even in a skillet.</p><p>They are not allowed to specify whether they want it on a disposable plate, a ceramic plate, a metal plate, or any other type of plate available.</p><p>Content Negotiation is the mechanism that allows you to create a restaurant that offer diners such choices and actually provide them.</p><h3>Categories</h3><p>While content negotiation enables you to offer your data in multiple formats, the formats can exist in three categories.</p><ol><li><strong>Media-Type category</strong>: This is when data is offered in such format as HTML, JSON, XML, plain text.</li></ol><p>Based on the explanations so far, this is what you currently understand by content negotiation.</p><p>2. <strong>Language category</strong>: This is when data is offered in different languages. US English, British English, German, Spanish.</p><p>You can code your data to be returned in diverse languages.</p><p>It’s still a form of content negotiation.</p><p>3. <strong>Encoding format</strong>: This is when the character encoding format of the data is also put into consideration and varied.</p><p>You can code your data to be returned as a UTF-8 encoded data.</p><p>You can as well vary it to be returned as a UTF-16 encoded data.</p><h3>Approaches to Content Negotiation</h3><p>In his <a href="https://maheshbonagiri.medium.com/spring-boot-and-content-negotiation-183b20eaa425">article</a> on Content Negotiation, Mahesh Bonagiri says that Content Negotiation can be implemented in the following ways:</p><p>A. <strong>Using Path Extension</strong>: This entails coding your API such that if the client adds extensions such as .json, .xml, .html, .txt to a URI, data in a representation corresponding to the extension will be returned.</p><p>This usually has the highest preference.</p><p>Examples are the below:</p><pre>github.com/[username].png<br>github.com/[username].keys<br>github.com/[username].gpg</pre><p>B. <strong>Using URL parameter</strong>: This entails coding your API such that if the client adds URL parameters such as format=xml or format=json to a request, data in a representation corresponding to the parameter will be returned.</p><p>This usually have the second highest preference.</p><p>Examples are the below:</p><pre>maps.googleapis.com/maps/api/staticmap?format=json<br>api.openweathermap.org/data/2.5/weather?units=metric<br>www.googleapis.com/youtube/v3/videos?alt=atom+xml</pre><p>C. <strong>Using Accept Headers</strong>: This entails coding your API such that if the client sets the <em>Accept</em> header to specify a preferred media type or a preferred language type or a preferred content encoding, data in a representation corresponding to the header value will be returned.</p><p>This is the method used in the HTTP protocol.</p><p>Examples are the below:</p><pre>GET https://api.github.com/repos/octocat/Hello-World<br>Accept: application/json<br>GET https://api.twitter.com/2/tweets/1234567890<br>Accept-Language: es<br>GET https://api.github.com/gists/GIST_ID<br>Accept-Encoding: gzip</pre><p>According to the <a href="https://www.w3.org/TR/dx-prof-conneg/">W3C</a>, when selecting a content mechanism, an API client may use the HTTP protocol (Accept headers), but it may also use other methods for providing instructions to the server (Path extensions, URL parameters).</p><p>URL parameters are useful for humans and machines where negotiation via HTTP is not practical. For example, when manually entering requests into web browsers.</p><h3>Importance of Content Negotiation</h3><p>Satyendra Jaiswal in his <a href="https://medium.com/@satyendra.jaiswal/content-negotiation-serving-multiple-representations-of-resources-0e39a54b6d7b">article </a>on content negotiation clearly outline the importance of content negotiation and they are as follows:</p><p>1. <strong>Content negotiation helps you to support diverse clients</strong>: For example, an API serves both a web application and a mobile app. The web app prefers JSON (Accept: application/json), while the mobile app prefers XML (Accept: application/xml). Content negotiation ensures that each client receives the desired representation.</p><p>2. <strong>Content negotiation enables data format flexibility</strong>: For example, a client with limited bandwidth may prefer a more compact data format like MessagePack (Accept: application/msgpack). Content negotiation allows your server to accommodate this preference.</p><p>3. <strong>Content negotiation enables language localization</strong>: For example, a global application supports multiple languages. The client specifies its preferred language using the Accept-Language header (Accept-Language: en-US). Content negotiation ensures that your server responds with content localized to the specified language.</p><h3>Controversies</h3><p>Some engineers are fully into the idea of content negotiation. Some are wary of it.</p><p>This was clearly exhibited in an hacker news thread <a href="https://news.ycombinator.com/item?id=38338033">“why I tend not to use content negotiation”</a>.</p><p>One commentator argued that browsers don’t always respect the <em>Accept</em> header especially when caching has been implemented or when the browser on its own caches the results.</p><p>Another commentator argued that some big CDNs don’t respect the <em>Accept</em> header.</p><p>Some commentators expressed disagreements over sharing the same endpoints between humans and machines which is what content negotiation facilitates.</p><p>For some engineers, content negotiation is something every website developer should implement. In his <a href="https://medium.com/@ijoeyguerra/content-negotiation-in-node-js-augmenting-express-js-78ea9de8bda0">article</a> on content negotiation, Joey Guerra argued that every website should be built to welcome content negotiation and respond with the requested representation for a resource.</p><p>Want to see how content negotiation is implemented in your prefered language/framework?</p><p>Make your pick.</p><p><a href="https://medium.com/@dennisthebusinessguru/implementing-content-negotiation-in-fastapi-371d03c59c02">FASTAPI</a></p><p><a href="https://medium.com/javarevisited/content-negotiation-for-reactive-web-services-in-spring-boot-3-0d8ee13fd5b4">Spring Boot</a></p><p><a href="https://medium.com/@softsusanta/how-to-set-up-content-negotiation-in-the-net-core-api-step-by-step-f9cba4d7fcfa">.NET Core</a></p><p><a href="https://medium.com/@ijoeyguerra/content-negotiation-in-node-js-augmenting-express-js-78ea9de8bda0">Node JS</a></p><p><a href="https://medium.com/@adegbengaagoro/implementing-content-negotiation-in-adonisjs-v5-e84d4fd14868">Adonis JS</a></p><p><a href="https://satish1v.medium.com/content-negotiation-with-asp-net-core-97c9e4a65d14">ASP.net Core</a></p><p><a href="https://medium.com/sagar-ganatras-blog/coldfusion-10-using-http-content-negotiation-to-invoke-a-rest-service-f349a2fff534">ColdFusion 10</a></p><p>Thanks for reading this article!</p><p>Leave a comment below if you have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa58e4eb1661" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>