The Wayback Machine - https://web.archive.org/web/20240822200816/https://www.geeksforgeeks.org/python-api-tutorial-getting-started-with-apis/
Open In App

Python API Tutorial: Getting Started with APIs

Last Updated : 10 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn about how Python API is used to retrieve data from various sources. Also, we will cover all concepts related to Python API from basic to advanced. Various websites provide weather data, Twitter provides data for research purposes, and stock market websites provide data for share prices.

PYTHON-API-TUTORIAL

Python API Tutorial

What is an API?

API stands for “Application Programming Interface.” In simple terms, it’s a set of rules and protocols that allow how different software applications can communicate and interact with each other. APIs define the methods and data formats that applications can use to request and exchange information. To retrieve data from a web server, a client application initiates a request, and the server responds with the requested data. APIs facilitate this communication by serving as intermediaries, allowing seamless integration between diverse software systems. In essence, APIs act as bridges that enable the smooth exchange of data and functionality, enhancing interoperability across various applications.

Prerequisites: Python, API

Making API Requests in Python

In order to work with API some tools are required such as requests so we need to first install them in our system.

Command to install ‘requests’:

pip3 install requests

Once we have installed it, we need to import it in our code to use it.

Command to import ‘requests’:

import requests

Let us understand the working of API with examples. First let us take a simple example.

Example 1: Extracting stock price by the help of API

In this Python program fetches the live stock data for “IBM” from the Alpha Vantage API using the 5-minute interval and prints the opening price.Here we make use of ‘requests’ to make a call and it is checked with the help of status code that whether our request was successful or not.Then the response is converted to python dictionary and the respected data is stored .

Python
import requests
import json
# Function to get live stock data for a symbol
def get_stock_data():
    url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&outputsize=full&apikey=demo"
    response = requests.get(url)
    
    # Check if the response is successful
    if response.status_code == 200:
        data = response.json()
        last_refreshed = data["Meta Data"]["3. Last Refreshed"]
        price = data["Time Series (5min)"][last_refreshed]["1. open"]
        return price
    else:
        return None

stock_prices = {}
price = get_stock_data()
symbol="IBM"
if price is not None:
    stock_prices[symbol] = price

print(f"{symbol}: {price}")

Output:

Python-API-Tutorial_-Getting-Started-with-APIs---Write

API

API Status Codes

As we know Status code tells us about what happened with our request, whether it was successfully executed or other was some error while processing it. They are returned with every request we place.

Codes related to “GET” request:

  • 200 OK: The server successfully processed the request, and the requested data is returned.
  • 201 Created: A new resource is created on the server as a result of the request.
  • 204 No Content: The request is successful, but there is no additional data to return.
  • 300 Multiple Choices: The requested resource has multiple representations, each with its own URL.
  • 302 Found (Temporary Redirect): The requested resource is temporarily located at a different URL.
  • 304 Not Modified: The client’s cached copy of the resource is still valid, and no re-download is necessary.
  • 400 Bad Request: The request has malformed syntax or contains invalid data, making it incomprehensible to the server.
  • 401 Unauthorized: Authentication is required, and the client’s credentials (e.g., API key) are missing or invalid.
  • 500 Internal Server Error: An unexpected server error occurred during request processing.
  • 502 Bad Gateway: Acting as a gateway or proxy, the server received an invalid response from an upstream server.

These status codes help communicate the outcome of API requests and guide developers and clients in understanding the results, errors, or necessary actions.

API Documentation

API Documentation is very essential and it helps in effective interaction. Here, we are using NewsAPI that provides us the information regarding various news of various countries and celebrities. To get news updates from NewsAPI, we need a special key called an API key. Think of it as a digital passcode that lets us access their news database. We’ve stored this key in a place called API_KEY.

Next, we’ve built a specific web address (or URL) that tells NewsAPI exactly what kind of news we want – in this case, top business headlines from the United States. It’s like telling a librarian you’re interested in the business section of a newspaper from a particular city.

After setting up this request, our code then sends a message to NewsAPI using this URL. It’s similar to clicking on a link to see a webpage. Once we send this message, NewsAPI replies with a status update. This status tells us if our request was successful or if there was any problem. We then simply print out this status to see if everything worked as expected.

Python
import requests
# Replace 'API_KEY' with your actual API key from NewsAPI
API_KEY = '3805f6bbabcb42b3a0c08a489baf603d'
url = f"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey={API_KEY}"
response = requests.get(url)
print(response.status_code)

Output

200

A successful request yields a ‘200’ status code, signifying success. The documentation also mentions that the API response comes in JSON format. Now, we will use response.json() method to get complete output in next section (Using API with Query).

Working with JSON Data

While working with APIs, it is very essential to know how to work with JSON data. Json universally works as the language of APIs that helps in providing a way to encode the data structures in a format that is easily interpreted by machines. Imagine browsing a news website. The data we see there—headlines, descriptions, images—is often structured in a format called JSON. It’s like the universal language that APIs speak.

Now, to make sense of this digital jigsaw puzzle, we’ve written a Python script. This script acts like a digital news curator: it reaches out to NewsAPI using a library called requests and fetches the latest business headlines from the US. Once it has this data, Python steps in, sorting and presenting it in a neat list. Think of it as a friendly librarian picking out the top three articles for us from a vast collection. This whole process not only gives us a glimpse into how APIs and JSON work hand in hand but also underscores the magic Python brings to the table in managing such tasks effortlessly.

Python
import json
import requests

def fetch_and_print_articles(api_url):
    response = requests.get(api_url)
    
    if response.status_code == 200:
        articles = response.json().get('articles', [])
        
        for index, article in enumerate(articles[:3], start=1):
            print(f"Article {index}:\n{json.dumps(article, sort_keys=True, indent=4)}\n")
    else:
        print(f"Error: {response.status_code}")

API_KEY = '3805f6bbabcb42b3a0c08a489baf603d'
api_endpoint = f"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey={API_KEY}"

fetch_and_print_articles(api_endpoint)

def jprint(obj):
    print(json.dumps(obj, sort_keys=True, indent=4))

# Example usage:
# jprint(response.json())

Output

Article 1:

{

“author”: “SamMobile, Asif Iqbal Shaik”,

“content”: “As tensions between China and the US escalate, the two countries are trying to counter each other through certain measures. The USA banned US-based chipmakers from exporting advanced chips and chip m\u2026 [+2001 chars]”,

“description”: “As tensions between China and the US escalate, the two countries are trying to counter each other through certain measures. …”,

“publishedAt”: “2023-12-18T09:07:00Z”,

“source”: {

“id”: null,

“name”: “SamMobile”

},

“title”: “China bans Apple and Samsung phones from government offices and firms – SamMobile – Samsung news”,

“url”: “https://www.sammobile.com/news/china-bans-apple-iphone-samsung-phones-government-offices-firms/”,

“urlToImage”: “https://www.sammobile.com/wp-content/uploads/2023/08/Samsung-Galaxy-Z-Flip-5-Fold-5-China-720×405.jpg”

}

Article 2:

{

“author”: “Katrina Bishop”,

“content”: “The 10-year Treasury note yield slipped further on Monday, as the final full trading week of 2023 gets underway.\r\nTraders continue to digest the unexpectedly dovish tone of the U.S. Federal Reserve l\u2026 [+1438 chars]”,

“description”: “The 10-year Treasury note yield continued to slip Monday as the final full trading week of 2023 gets underway.”,

“publishedAt”: “2023-12-18T08:04:15Z”,

“source”: {

“id”: null,

“name”: “CNBC”

},

“title”: “10-year Treasury yield slip further after Fed’s ‘big shift’ – CNBC”,

“url”: “https://www.cnbc.com/2023/12/18/10-year-treasury-yield-slip-further-after-feds-big-shift.html”,

“urlToImage”: “https://image.cnbcfm.com/api/v1/image/107347379-17025005642023-12-13t204555z_488020625_rc2jw4a133y9_rtrmadp_0_usa-stocks.jpeg?v=1702500622&w=1920&h=1080”

}

Article 3:

{

“author”: “Hakyung Kim”,

“content”: “U.S. stock futures climbed on Monday morning after the three major averages notched their seventh straight week of gains. The Dow Jones Industrial Average recorded a new intraday record, and the Nasd\u2026 [+1488 chars]”,

“description”: “The Dow Jones Industrial Average recorded a new intraday record on Friday, and the Nasdaq 100 had a new closing high.”,

“publishedAt”: “2023-12-18T05:43:00Z”,

“source”: {

“id”: null,

“name”: “CNBC”

},

“title”: “Stock futures are all rise after major averages rally for seven consecutive weeks: Live updates – CNBC”,

“url”: “https://www.cnbc.com/2023/12/17/stock-futures-are-little-changed-after-major-averages-rally-for-seven-consecutive-weeks-live-updates.html”,

“urlToImage”: “https://image.cnbcfm.com/api/v1/image/107347379-17025005642023-12-13t204555z_488020625_rc2jw4a133y9_rtrmadp_0_usa-stocks.jpeg?v=1702500622&w=1920&h=1080”

}

Using API with Query

When interacting with an API, especially one as popular as NewsAPI, it’s essential to know how to specify and tailor the data you want to retrieve. In this code snippet, we’re making use of the NewsAPI to fetch top headlines specifically for the United States. To communicate with the NewsAPI, we have the endpoint URL defined as API_URL. Additionally, each developer or user is provided with an API key for authentication purposes. Here, the API key is stored in the API_KEY variable.

However, simply knowing the endpoint and having an API key isn’t enough. Often, APIs allow for a level of customization, letting users specify certain parameters to refine their request. This is where the params dictionary comes into play. In this case, we’re interested in fetching news from the U.S., so we set the country parameter to “us”. Additionally, to ensure our request is authenticated and linked to our account, we include the API key in the parameters.

Python
import requests

# API endpoint and key
API_URL = "https://newsapi.org/v2/top-headlines"
API_KEY = "3805f6bbabcb42b3a0c08a489baf603d"

# Parameters for the API request
params = {
    "country": "us",
    "apiKey": API_KEY
}

# Making the API request
response = requests.get(API_URL, params=params)

# Checking if the request was successful
if response.status_code == 200:
    # Printing the JSON response
    print(response.json())
else:
    print(f"Error: {response.status_code}")

Output

{

“status”: “ok”,

“totalResults”: 37,

“articles”: [

{

“source”: {

“id”: null,

“name”: “BBC News”

},

“author”: null,

“title”: “Iceland volcano erupts on Reykjanes peninsula – BBC.com”,

“description”: “The eruption, in south-west Iceland, led to half the sky being \”lit up in red\”, an eyewitness says.”,

“url”: “https://www.bbc.com/news/world-europe-67756413”,

“urlToImage”: “https://ichef.bbci.co.uk/news/1024/branded_news/13806/production/_132087897_helicopterstill.jpg”,

“publishedAt”: “2023-12-19T08:24:57Z”,

“content”: “By Marita Moloney & Oliver SlowBBC News\r\nSpectacular helicopter shots show the eruption on the island’s coast\r\nA volcano has erupted on the Reykjanes peninsula of south-west Iceland after weeks o… [+5343 chars]”

},

{

“source”: {

“id”: null,

“name”: “[Removed]”

},

“author”: null,

“title”: “[Removed]”,

“description”: “[Removed]”,

“url”: “https://removed.com”,

“urlToImage”: null,

“publishedAt”: “1970-01-01T00:00:00Z”,

“content”: “[Removed]”

},

{

“source”: {

“id”: “financial-times”,

“name”: “Financial Times”

},

“author”: null,

“title”: “Google to pay $700mn in antitrust settlement over Android app store – Financial Times”,

“description”: “Tech giant agrees to alternative billing methods for Play Store in ‘unprecedented’ case from US states”,

“url”: “https://www.ft.com/content/e7f7c7d6-79b4-4de4-aa4b-f656546a91ca”,

“urlToImage”: null,

“publishedAt”: “2023-12-19T06:41:18Z”,

“content”: “Keep abreast of significant corporate, financial and political developments around the world. Stay informed and spot emerging risks and opportunities with independent global reporting, expert comment… [+30 chars]”

}

]

}

Example 2: How To Track ISS (International Space Station) Using Python?

In this example we will discuss how to track the current location of ISS(International Space Station) and then maps the location.

Required Module

Python
# Python's built-in support for JSON
import json 
# Python turtle library for creating designs and images
import turtle  
# Python module for fetching URLs
import urllib.request  
# Python module for time-related functions
import time  
# Python module for opening URLs in a web browser
import webbrowser  
# Python module for retrieving latitude and longitude
import geocoder  

Explanation of Library Usage:

  • json: Handling JSON data received from the ISS API.
  • turtle: Creating a simple map to display the ISS location.
  • urllib.request: Fetching data from the ISS API.
  • time: Adding time-related functionality, such as delays.
  • webbrowser: Opening the map in a web browser.
  • geocoder: Retrieving the latitude and longitude of locations.

Getting Started With API Key

So now there is a problem with tracking ISS because it travels at a speed of almost 28000km/h. Thus, it takes only 90 minutes to complete 1 rotation around the earth. At such a speed, it becomes quite difficult to lock the exact coordinates. So here comes the API to solve this issue. API acts as an intermediate between the website and the program, thus providing the current time data for the program.

In our case, API will provide us with the current location of ISS in earth’s orbit, so visit the link below as an API link for astronaut info.

url = "http://api.open-notify.org/astros.json" 

Accessing Data

Use urllib.request.urlopen() function inorder to open the API url and json.loads(.read()) function to read the data from the URL.

Python
import json
import turtle
import urllib.request
import time
import webbrowser
import geocoder

url = "http://api.open-notify.org/astros.json"
response = urllib.request.urlopen(url)
result = json.loads(response.read())
result

Output:

{"number": 10, "people": [{"craft": "ISS", "name": "Sergey Prokopyev"},
{"craft": "ISS", "name": "Dmitry Petelin"},
{"craft": "ISS", "name": "Frank Rubio"},
{"craft": "Tiangong", "name": "Jing Haiping"},
{"craft": "Tiangong", "name": "Gui Haichow"},
{"craft": "Tiangong", "name": "Zhu Yangzhu"},
{"craft": "ISS", "name": "Jasmin Moghbeli"},
{"craft": "ISS", "name": "Andreas Mogensen"},
{"craft": "ISS", "name": "Satoshi Furukawa"},
{"craft": "ISS", "name": "Konstantin Borisov"}], "message": "success"}



Create.txt file for astronauts info

Create iss.text file using an open() function in write mode and write the result(names & numbers of astronauts) as data inside the file.

Python
file = open("iss.txt", "w")
file.write(
"There are currently " + str(result["number"]) +
" astronauts on the ISS: \n\n")

people = result["people"]
for p in people:
    file.write(p['name'] + " - on board" + "\n")

Current Latitude and Longitude of User

Use geocoder.ip(‘me’) to know your current location in terms of latitude and longitude and after that using write the data in the file and then close the file using the file.close() function.

Python
# print long and lat
g = geocoder.ip('me')
file.write("\nYour current lat / long is: " + str(g.latlng))
file.close()
webbrowser.open("iss.txt")

Setting Up The World Map

Use turtle.screen() function to get access to the screen, then use screen.setup() to set the size and position of the output window. Use screen.setworldcoordinates() function to set the coordinates of all 4 corners on x, y-axis so that when iss reach out from reaches they appear again from another edge.

Python
screen = turtle.Screen()
screen.setup(1280, 720)
screen.setworldcoordinates(-180, -90, 180, 90)

Set map as background pic using screen.bgpic() function and set iss image as turtle shape using screen.register_shape() function. Use it as an object and assign it as a shape using iss.shape() function, then set the angle of shape using iss.setheading() function. iss.penup() function indicates that their drawings. Thus, the turtle stops. The file can be downloaded:

  • map.gif
  • iss.gif

Code:

Python
# load the world map image
screen.bgpic("images\map.gif")
screen.register_shape("images\iss.gif")
iss = turtle.Turtle()
iss.shape("images\iss.gif")
iss.setheading(45)
iss.penup()

Access the current status of ISS using the API below:

 url = "http://api.open-notify.org/iss-now.json"

Extract the current location of ISS in terms of latitude and longitude from the above API. This script below runs inside the while loop so you can see the updated position and movement of the ISS until you stop the program.

Python
# load the current status of the ISS in real-time
url = "http://api.open-notify.org/iss-now.json"
response = urllib.request.urlopen(url)
result = json.loads(response.read())

# Extract the ISS location
location = result["iss_position"]
lat = location['latitude']
lon = location['longitude']

# Output lon and lat to the terminal in the
# float format
lat = float(lat)
lon = float(lon)
print("\nLatitude: " + str(lat))
print("\nLongitude: " + str(lon))

Update the position of ISS every 5 seconds by refreshing the latitude and longitude value from API.

Python
# Update the ISS location on the map
iss.goto(lon, lat)

# Refresh each 5 seconds
time.sleep(5)

Below is the full implementation.

Python
# json convert the python dictionary
# above into a json
import json
import turtle

# urllib.request fetch URLs using
# a variety of different protocols
import urllib.request
import time

# webbrowser provides a high-level interface
# to allow displaying Web-based documents
# to users
import webbrowser

# geocoder takes the data and locate these
# locations in the map
import geocoder

url = "http://api.open-notify.org/astros.json"
response = urllib.request.urlopen(url)
result = json.loads(response.read())
file = open("iss.txt", "w")
file.write("There are currently " +
            # prints number of astronauts
        str(result["number"]) + " astronauts on the ISS: \n\n")
people = result["people"]

# prints names of crew
for p in people:
    file.write(p['name'] + " - on board" + "\n")
# print long and lat
g = geocoder.ip('me')
file.write("\nYour current lat / long is: " + str(g.latlng))
file.close()
webbrowser.open("iss.txt")

# Setup the world map in turtle module
screen = turtle.Screen()
screen.setup(1280, 720)
screen.setworldcoordinates(-180, -90, 180, 90)

# load the world map image
screen.bgpic("images/map.gif")
screen.register_shape("images\iss.gif")
iss = turtle.Turtle()
iss.shape("images\iss.gif")
iss.setheading(45)
iss.penup()

while True:

    # load the current status of the ISS in real-time
    url = "http://api.open-notify.org/iss-now.json"
    response = urllib.request.urlopen(url)
    result = json.loads(response.read())

    # Extract the ISS location
    location = result["iss_position"]
    lat = location['latitude']
    lon = location['longitude']

    # Ouput lon and lat to the terminal
    lat = float(lat)
    lon = float(lon)
    print("\nLatitude: " + str(lat))
    print("\nLongitude: " + str(lon))

    # Update the ISS location on the map
    iss.goto(lon, lat)

    # Refresh each 5 seconds
    time.sleep(5)

Output:

Crew Information: Here is info on the onboarded crew members along with their names.

Python-API-Tutorial_-Getting-Started-with-APIs---Write-(1)

API

ISS Location: Here is a screenshot of the moving ISS i.e orbiting around the earth. You can see it by zooming in on the screenshot.

Getting Started with APIs

API

ISS Moving look: Here you can see the ISS moving every 5 seconds.

Getting Started with APIs in Python

API

Reasons to use API

Here the question arises why use API? if we can get data in the a form of CSV file from the resource. To understand this let us look at the examples below:

  • Change in Data: Suppose we are using API to collect data about the temperature of all the cities in India. As the temperature changes with time, a new CSV file is to be downloaded every time we want the information and it will require a lot of bandwidth and a lot of time to process the same. The same data can be collected with the API very easily and in less time.
  • Size of data: At certain times we require only a small part of the large data. For example, if we want to get the comments on a tweet then we don’t need to download the whole dataset of Twitter. The required task can be done very easily with the help of Twitter API. APIs enable the extraction of specific, targeted data, minimizing unnecessary data transfer and optimizing the process for tasks that require only a fraction of the available information.

Conclusion

In conclusion , an API (Application Programming Inferface) serves a protocol and tools that enables different software applications to communicate and protocols interact with each other. APIs are instrumental in enabling the interoperability of applications, fostering innovation, and streamlining the development process by providing standardized interfaces for communication and data exchange.

Python API Tutorial: Getting Started with APIs – FAQs

How Do I Start an API in Python?

To start building an API in Python, you can use frameworks like Flask, Django REST Framework, or FastAPI. These frameworks provide tools and libraries that make it easier to develop, manage, and serve APIs. Here’s a basic example of how to start an API using Flask:

Example using Flask:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api', methods=['GET'])
def home():
return jsonify({'message': 'Hello, World!'})

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

This script creates a simple API that returns a JSON response when visited at the route “/api”.

What is API and How It Works in Python?

An API (Application Programming Interface) in Python (and generally) serves as a gateway for programming components to interact with each other. In web development, an API provides a set of rules and mechanisms through which different software applications can communicate over a network. APIs handle requests and responses, allowing users to fetch, insert, delete, or update data.

How to Connect API in Python?

To connect to an external API in Python, you typically use the requests library, which simplifies HTTP requests. Here’s how to make a GET request to an API:

Example using requests:

import requests

url = "http://api.example.com/data"
response = requests.get(url)
data = response.json() # Assuming the response is in JSON format
print(data)

This code snippet fetches data from the specified URL and converts the JSON response to a Python dictionary.

How to Get API Data in Python?

Getting data from an API involves sending HTTP requests. The requests library can be used to send these requests and handle responses. Here’s a detailed example for fetching data:

import requests

# Define the API endpoint
url = "https://api.example.com/items"

# Send a GET request
response = requests.get(url)

# Convert the response to JSON format
items = response.json()

# Use the data
for item in items:
print(item)

This code sends a request to the “items” endpoint of an API and prints each item from the JSON response.

How to Create a FastAPI in Python?

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. Here’s a basic example to create an API using FastAPI:

Example using FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
return {"Hello": "World"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

# Run the server
# Command to run: `uvicorn filename:app --reload`

This FastAPI application includes two routes and demonstrates how to handle path parameters and optional query parameters. To run this FastAPI app, save the script, install FastAPI and uvicorn (an ASGI server), and execute it using the command provided in the comment.



Similar Reads

Python | Getting started with SymPy module
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python. SymPy only depends on mpmath, a pure Python library for arbitrary floating point arithmetic, making
4 min read
Python | Getting started with psycopg2-PostGreSQL
PostgreSQL is a powerful, open source object-relational database system. PostgreSQL runs on all major operating systems. PostgreSQL follows ACID property of DataBase system and has the support of triggers, updatable views and materialized views, foreign keys. To connect PostgreSQL we use psycopg2 . It is the best and most friendly Database adapter
1 min read
Getting started with Python for Automated Trading
Automated Trading is the terminology given to trade entries and exits that are processed and executed via a computer. Automated trading has certain advantages: Minimizes human intervention: Automated trading systems eliminate emotions during trading. Traders usually have an easier time sticking to the strategy by holding emotions in check. Backtest
3 min read
Getting Started with Plotly-Python
The Plotly Python library is an interactive open-source library. This can be a very helpful tool for data visualization and understanding the data simply and easily. plotly graph objects are a high-level interface to plotly which are easy to use. It can plot various types of graphs and charts like scatter plots, line charts, bar charts, box plots,
4 min read
Getting Started with Python OpenCV
Computer Vision is one of the techniques from which we can understand images and videos and can extract information from them. It is a subset of artificial intelligence that collects information from digital images or videos. Python OpenCV is the most popular computer vision library. By using it, one can process images and videos to identify object
15+ min read
Getting Started on Heroku with Python
Heroku is a cloud platform as a service supporting several programming languages where a user can deploy, manage and scale their applications. It is widely used to deploy server-based web applications, APIs, discord bots, and more. So today in this tutorial, we'll be deploying a simple flask app to Heroku from start, and learn how it works. Ways to
3 min read
Getting Started with Competitive Programming in Python
Python is a great option for programming in Competitive Programming. First off, its easy-to-understand and concise grammar enables quicker development and simpler debugging. The huge standard library of Python offers a wide range of modules and functions that can be used to effectively address programming difficulties. Python also offers dynamic ty
11 min read
Getting Started With ImageIO Library in Python
Imageio is a Python library that provides an easy interface to read and write a wide range of image and video data, including animated images, volumetric data, and scientific formats. It is cross-platform. Installation: This module does not come built-in with Python. To install it type the below command in the terminal. pip install imageioRequireme
3 min read
Getting Started With Nose Testing in Python
Testing is essential for software development, ensuring that programs work reliably. Python offers various testing frameworks, but Nose stands out for being simple, flexible, and easy to extend. This article will explore Nose testing, covering its fundamentals, fixtures, and advanced features. Table of Content What is Nose?Why Choose Nose in Python
4 min read
Getting Started With Unit Testing in Python
In Python, unit tests are the segments of codes that are written to test other modules and files that we refer to as a unit. Python Unit Testing is a very important part of the software development process that helps us to ensure that the code works properly without any errors. In this article, we will learn about Python Testing with the help of ex
8 min read
Getting started with Jupyter Notebook | Python
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Jupyter has support for over 40 different programming languages and Python is one of them. Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyt
7 min read
Getting Started with Python Programming
Python is a high-level, interpreted, and general-purpose programming language. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability and simplicity, making it an excellent language for beginners and experienced developers. Getting Started with Python is easy due to its straightforward syntax and extensive
9 min read
Getting Started with Pygame
Pygame is a free-to-use and open-source set of Python Modules. And as the name suggests, it can be used to build games. You can code the games and then use specific commands to change it into an executable file that you can share with your friends to show them the work you have been doing. It includes computer graphics and sound libraries designed
3 min read
Getting started with Django
Python Django is a web framework that is used to create web applications very efficiently and quickly. Django is called a battery included framework because it contains a lot of in-built features such as Django Admin Interface, default database - SQLite3, etc. Django provides various ready-made components such as a way to handle user authentication
15+ min read
Getting started with Jinja Template
This article introduces Jinja and then describes the basics of working with it which includes how to render templates using Jinja and Python3, passing data to the template through arguments, and basic Jinja syntax (delimiters, expressions, control structures - decisions and loops). A few examples including creating a simple static HTML page are pre
8 min read
Getting started with PySoundFile
PySoundFile is a Python module used for reading and writing audio files, see an audio file as NumPy array including of pitches and all. This module can read the audio file i.e. it extracts the NumPy array from audio(.wav files) and able to write it too Installation: Run the following pip command: pip install PySoundFile PySoundFile supports all the
3 min read
Getting Started with Pytest
Python Pytest is a framework based on Python. It is mainly used to write API test cases. It helps you write better programs. In the present days of REST services, Pytest is mainly used for API testing even though we can use Pytest to write simple to complex test cases, i.e., we can write codes to test API, UI, database, etc. In this article, we wil
5 min read
Getting Started With Object Tracking Using OpenCV
OpenCV, developed by Intel in the early 2000s, is a popular open-source computer vision library used for real-time tasks. It offers various features like image processing, face detection, object detection, and more. In this article, we explore object-tracking algorithms and how to implement them using OpenCV and Python to track objects in videos. G
4 min read
Getting Started with Conda
Let us start our journey to Conda, a versatile and indispensable tool for data scientists, analysts, and developers. This sophisticated tool goes beyond the limitations of traditional management systems, delivering a holistic solution that simplifies the process of configuring, managing, and deploying software packages and dependencies life is hass
15+ min read
Getting Started with OpenCV CUDA Module
OpenCV is an well known Open Source Computer Vision library, which is widely recognized for computer vision and image processing projects. The OpenCV CUDA (Compute Unified Device Architecture ) module introduced by NVIDIA in 2006, is a parallel computing platform with an application programming interface (API) that allows computers to use a variety
8 min read
Parsing XML with DOM APIs in Python
The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Parsing XML with DOM APIs in python is pretty simple. For the purpose of example we will create a sample XML document (sample.xml) as bel
2 min read
Mocking external APIs in Python
Consider yourself developing software that needs an external API as a dependency and while testing we found that the API is not functional for some reason. As we know testing is one of the most critical phases in SDLC (Software Development Life Cycle) and without the API dependency, testing could not be performed. We have a few solutions like waiti
4 min read
Build APIs with Falcon in Python
In the sector of web development, building a sturdy and green API is vital. APIs (Application Programming Interfaces) act as a bridge between software program structures, allowing for easy verbal exchange and record change. Python, with its flexibility and flexibility, is a popular choice for growing APIs. Among the numerous Python frameworks to be
6 min read
Adding Pagination in APIs - Django REST Framework
Imagine you have huge amount of details in your database. Do you think that it is wise to retrieve all at once while making an HTTP GET request? Here comes the importance of the Django REST framework pagination feature. It facilitates splitting the large result set into individual pages of data for each HTTP request. So when we make an HTTP request
8 min read
Building RESTful APIs with FastAPI
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. There is Another famous framework for doing the same is Flask, which is also Python-based. In this article, we will focus on creating a RESTful API using FastAPI. In this article, we will learn how to create a basic ToDo List API using FastAPI. FastAPI is a
5 min read
Testing APIs with Swagger
API testing in Swagger involves validating the functionality and performance of APIs developed using the Swagger framework. Swagger, now known as the OpenAPI Specification, provides a standardized way to document and define RESTful APIs. API testing in Swagger focuses on verifying that the API endpoints adhere to the specified OpenAPI documentation
6 min read
Building Mock APIs with Swagger
This step-by-step tutorial for constructing a mock API in Python using Swagger. In this article, we'll step through the full process, from defining our API with Swagger to developing and testing a mock server. Whether you're an experienced developer or just starting started, this article will show you how to construct Mock APIs with Swagger. The pr
8 min read
Documenting RESTful APIs with Swagger
RESTful APIs play an important role in communicating between various software components. The interface used to consume APIs significantly impacts the chances of achieving business and technological objectives. In this article, we'll dive into the importance of RESTful API documentation and how Swagger simplifies this process. Documenting RESTful A
9 min read
Documenting Websocket APIs with Swagger
WebSocket APIs offer a powerful way to create real-time, interactive applications by enabling bidirectional communication between clients and servers. Documenting these APIs is crucial for developers to understand and utilize them effectively. Swagger (now known as OpenAPI) is a widely used framework for API documentation, but it primarily focuses
3 min read
Building APIs using FastAPI with Django
Combining FastAPI and Django can leverage the strengths of both frameworks: FastAPI's high performance for building APIs and Django's powerful ORM and admin interface. In this guide, we'll outline how to integrate FastAPI into a Django project to build high-performance APIs. In this article, we will combine the strengths of both Django and FastAPI
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg