18. APIs and Networking

APIs and networking allow applications to:

  • Communicate with each other
  • Exchange data
  • Connect over networks

Python provides powerful libraries for:

  • REST APIs
  • HTTP requests
  • JSON handling
  • Authentication
  • Socket programming

What is an API?

API stands for:

Application Programming Interface

An API allows software applications to communicate.

Examples:

  • Weather apps
  • Payment gateways
  • Social media integrations

REST APIs

REST stands for:

Representational State Transfer

REST APIs use HTTP methods:

MethodPurpose
GETRetrieve data
POSTCreate data
PUTUpdate data
DELETERemove data

Example API URL

https://api.example.com/users

Using requests Library

The requests library is used to send HTTP requests.


Install Requests

pip install requests

Import Requests

import requests

GET Request

Used to fetch data.

import requests

response = requests.get(
"https://api.github.com"
)

print(response.status_code)
print(response.text)

Response Status Codes

CodeMeaning
200Success
404Not found
500Server error
401Unauthorized

JSON Response

Most APIs return JSON data.

data = response.json()

print(data)

POST Request

Used to send data.

import requests

data = {
"name": "Aditya",
"course": "Python"
}

response = requests.post(
"https://httpbin.org/post",
json=data
)

print(response.json())

PUT Request

Used to update data.

data = {
"name": "Updated Name"
}

response = requests.put(
"https://httpbin.org/put",
json=data
)

print(response.status_code)

DELETE Request

Used to remove data.

response = requests.delete(
"https://httpbin.org/delete"
)

print(response.status_code)

Request Headers

Headers provide additional information.

headers = {
"User-Agent": "Python App"
}

response = requests.get(
"https://api.github.com",
headers=headers
)

Query Parameters

params = {
"page": 1,
"limit": 5
}

response = requests.get(
"https://httpbin.org/get",
params=params
)

print(response.url)

JSON Handling

JSON stands for:

JavaScript Object Notation

Used for storing and exchanging data.


Python Dictionary to JSON

import json

data = {
"name": "Aditya",
"age": 25
}

json_data = json.dumps(data)

print(json_data)

JSON to Python Dictionary

import json

text = '{"name":"Aditya"}'

data = json.loads(text)

print(data)

Read JSON File

import json

with open("data.json", "r") as file:

data = json.load(file)

print(data)

Write JSON File

import json

data = {
"course": "Python"
}

with open("data.json", "w") as file:

json.dump(data, file, indent=4)

API Authentication

Many APIs require authentication for security.

Common authentication methods:

  • API Keys
  • Tokens
  • OAuth

API Key Authentication

headers = {
"Authorization": "Bearer YOUR_API_KEY"
}

response = requests.get(
"https://api.example.com/data",
headers=headers
)

Token Authentication Example

token = "your_token"

headers = {
"Authorization": f"Bearer {token}"
}

response = requests.get(
"https://api.example.com/profile",
headers=headers
)

Basic Authentication

from requests.auth import HTTPBasicAuth

response = requests.get(
"https://api.example.com",
auth=HTTPBasicAuth(
"username",
"password"
)
)

Handling API Errors

import requests

try:

response = requests.get(
"https://api.github.com"
)

response.raise_for_status()

print(response.json())

except requests.exceptions.RequestException as e:
print("Error:", e)

Socket Programming Basics

Socket programming enables communication between devices over a network.

Used for:

  • Chat applications
  • Multiplayer games
  • Real-time systems

Python provides:

socket

module.


Import Socket Module

import socket

Socket Server Example

import socket

server = socket.socket()

server.bind(("localhost", 12345))

server.listen(1)

print("Waiting for connection...")

client, address = server.accept()

print("Connected:", address)

client.send(
"Hello Client".encode()
)

client.close()

Socket Client Example

import socket

client = socket.socket()

client.connect(("localhost", 12345))

message = client.recv(1024)

print(message.decode())

client.close()

UDP Socket Example

import socket

sock = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)

sock.sendto(
b"Hello",
("localhost", 12345)
)

Practical Example

Weather API Example

import requests

url = "https://api.openweathermap.org/data/2.5/weather"

params = {
"q": "Delhi",
"appid": "YOUR_API_KEY"
}

response = requests.get(
url,
params=params
)

data = response.json()

print(data)

Advantages of APIs

✅ Easy data exchange
✅ Connect multiple applications
✅ Automation support
✅ Real-time communication
✅ Scalable integration


Best Practices

✅ Secure API keys
✅ Handle API errors properly
✅ Use HTTPS APIs
✅ Validate JSON responses
✅ Avoid excessive API requests


Summary

In this chapter you learned:

✅ REST APIs
✅ Using requests
✅ JSON handling
✅ API authentication
✅ Socket programming basics