Complete Python API Guide: Usage, Building & Deployment

目次

1. Introduction

API (Application Programming Interface) is a mechanism that allows software to communicate with each other. In recent years, many web services and applications provide APIs, enabling developers to retrieve data and integrate systems. Python, with its simple syntax and extensive libraries, is one of the programming languages well suited for using and building APIs. In this article, we will explain the fundamentals of “Python APIs,” covering how to use APIs with Python and how to build them.

1.1 What is an API?

API (Application Programming Interface) is a mechanism that allows different software and services to share data and functionality. For example, a weather app retrieves meteorological data by using an external weather information service’s API. APIs are primarily used for the following purposes.
  • Data retrieval: fetching social media posts, weather forecasts, stock prices, etc.
  • Data submission: registering user information, submitting forms, processing payments, and so on.
  • System integration: connecting different apps and services.
There are many types of APIs, but the most common is the REST API (Representational State Transfer API). It uses the HTTP protocol, allowing clients (apps or browsers) and servers to exchange requests and responses.

1.2 Benefits of Using and Creating APIs with Python

Python is a programming language well suited for both consuming and creating APIs. Here are a few reasons.

1.2.1 Simple code for consuming APIs

Python includes the requests library as a standard tool, allowing you to call an API and retrieve data in just a few lines of code.
import requests

response = requests.get("https://api.example.com/data")
print(response.json())  # Display the retrieved data
In this way, Python makes it easy to interact with APIs.

1.2.2 Powerful web frameworks available

Python offers several robust frameworks for building APIs. The most popular are Flask and FastAPI.
  • Flask: a lightweight and simple web framework. Even beginners can easily build APIs.
  • FastAPI: leverages modern Python features (type hints) to create fast and secure APIs.

1.2.3 Rich libraries and extensibility

Python provides a wealth of libraries that pair well with APIs, covering data processing, machine learning, cloud service integration, and more.
  • requests: simplifies communication with APIs
  • json: handles JSON data from API responses
  • Flask / FastAPI: frameworks suited for building APIs
  • SQLAlchemy: ORM for connecting databases and APIs
By leveraging these, you can develop APIs efficiently with Python.

1.3 What You’ll Learn in This Article

This article provides detailed coverage of both how to use APIs with Python and how to build them.
  • How to use APIs with Python
  • API communication using the requests library
  • Processing API responses (JSON parsing)
  • Implementing error handling
  • How to create APIs with Python
  • Building web APIs with Flask / FastAPI
  • Integrating with databases
  • Implementing authentication and security measures
  • Practical uses of Python APIs
  • Deploying to cloud environments (Heroku, AWS Lambda)
  • Optimizing for performance improvements
Whether you want to leverage APIs with Python or build your own, this article offers practical knowledge. In the next section, we’ll walk through how to use APIs with Python with concrete code examples.

2. How to Use the Python API (Beginner-friendly)

In Python, you can call external APIs to retrieve or send data. This section explains the basic ways to use APIs with Python. Specifically, it covers the following topics.
  • How to Call APIs in Python
  • HTTP requests using the requests library
  • Processing API responses
  • Error handling and mitigation

2.1 What is an API? Basic Concepts in Python

An API (Application Programming Interface) is an interface that allows different software to exchange data. For example, using a weather forecast API lets you retrieve weather data for a specific region. API communication uses HTTP requests. The most common request types are:
MethodDescription
GETRetrieve data from the server
POSTSend data to the server
PUTUpdate existing data
DELETEDelete data
In Python, you can easily call APIs using the requests library.

2.2 How to Call APIs in Python

To use APIs in Python, you use the requests library. It is a library that makes sending HTTP requests easy. First, if you haven’t installed the library, install it with the following command.
pip install requests

2.2.1 GET request using the requests library

A GET request retrieves data from the server. For example, to fetch random user information using a free API, you would write:
import requests

url = "https://randomuser.me/api/"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)  # Display JSON data
else:
    print("Error:", response.status_code)

2.2.2 Sending data with a POST request

To send data to an API, use a POST request. For example, to send dummy user information to a server, you would write:
import requests

url = "https://httpbin.org/post"
data = {
    "name": "Taro Yamada",
    "email": "taro@example.com"
}

response = requests.post(url, json=data)

if response.status_code == 200:
    print("Success:", response.json())
else:
    print("Error:", response.status_code)

2.3 Processing API Responses (JSON Parsing)

Many APIs return responses in JSON (JavaScript Object Notation) format. In Python, you can easily parse JSON data using the json module.
import requests

url = "https://randomuser.me/api/"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    user = data["results"][0]  # Retrieve user information
    print("Name:", user["name"]["first"], user["name"]["last"])
    print("Country:", user["location"]["country"])
else:
    print("Error:", response.status_code)

2.4 Error Handling and Mitigation

When using APIs, failing to implement proper error handling can cause the program to crash if unexpected errors occur.

2.4.1 Checking HTTP Status Codes

API responses include HTTP status codes. Common codes are:
Status CodeDescription
200OK
400Client error (Bad Request)
401Authentication error (Unauthorized)
403Forbidden
404URL not found (Not Found)
500Internal server error (Internal Server Error)
If an error occurs, appropriate handling is required.
import requests

url = "https://randomuser.me/api/"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)
elif response.status_code == 404:
    print("Error: Page not found")
elif response.status_code == 500:
    print("Server error occurred")
else:
    print(f"Error: {response.status_code}")

2.4.2 Timeout Handling

Network issues can cause API responses to be delayed. In such cases, you can set a timeout on the request to treat it as an error after a certain period.
import requests

url = "https://randomuser.me/api/"

try:
    response = requests.get(url, timeout=5)  # Set a 5-second timeout
    response.raise_for_status()  # Raise exception if status code indicates error
    data = response.json()
    print(data)
except requests.exceptions.Timeout:
    print("Error: Timeout occurred")
except requests.exceptions.RequestException as e:
    print("Error:", e)

Summary

This section explained how to use APIs with Python.
  • Basic concepts of APIs
  • GET/POST requests using the requests library
  • JSON parsing of API responses
  • Error handling and timeout processing
Understanding these will enable you to leverage various APIs.
侍エンジニア塾

3. How to Create an API with Python [Flask & FastAPI]

In Python, there are several frameworks for building APIs. Among them, we will explain how to create an API using the particularly popular Flask and FastAPI. This section covers the following topics.
  • Basic workflow for creating a Web API
  • Building a simple API with Flask
  • Building a high-performance API with FastAPI
  • Integration with databases
  • API security measures

3.1 How to Build a Web API?

When creating an API, development typically follows these steps.
  1. Choosing a framework (Flask / FastAPI, etc.)
  2. Designing endpoints (which URLs provide which data)
  3. Defining requests and responses (exchange data in JSON format)
  4. Integrating with a database (use SQL or NoSQL as needed)
  5. Authentication and security measures (use API keys or JWTs)
Now, let’s walk through how to create an API using Flask and FastAPI.

3.2 Building a Simple API with Flask

Flask is a simple, lightweight web framework that is well suited for quickly building small-scale APIs.

3.2.1 Installing Flask

To use Flask, first install the library.
pip install flask

3.2.2 Simple API with Flask

The following code is an example of a simple API using Flask.
from flask import Flask, jsonify

app = Flask(__name__)

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

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

Code Explanation

  1. Create an instance of the Flask class
  2. Define an API endpoint using the @app.route decorator
  3. Return a JSON-formatted response using jsonify()
  4. Start the local server with app.run(debug=True)
When you run this script and access http://127.0.0.1:5000/api/hello, a JSON response containing “Hello, World!” is returned.

3.3 Building a High-Performance API with FastAPI

FastAPI is a modern framework that leverages type hints introduced in Python 3.7 and later to build fast and secure APIs.

3.3.1 Installing FastAPI

To use FastAPI, install the libraries with the following command.
pip install fastapi uvicorn
(uvicorn is an ASGI server for running FastAPI apps)

3.3.2 Simple API with FastAPI

The following code is a basic API example using FastAPI.
from fastapi import FastAPI

app = FastAPI()

@app.get("/api/hello")
def hello():
    return {"message": "Hello, FastAPI!"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

3.4 Integrating Databases with APIs

When creating an API, you often need to store or retrieve data from a database.

3.4.1 Database Integration with SQLite and SQLAlchemy

In Python, you can simplify database operations by using SQLAlchemy. First, install SQLAlchemy.
pip install sqlalchemy sqlite
Next, create an API that combines Flask and SQLAlchemy.
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)

@app.route("/api/users", methods=["GET"])
def get_users():
    users = User.query.all()
    return jsonify([{"id": user.id, "name": user.name} for user in users])

if __name__ == "__main__":
    db.create_all()
    app.run(debug=True)

3.5 API Security Measures

When publishing an API, you need to implement robust security measures. Keep the following points in mind.

3.5.1 Implementing Authentication and Authorization

  • Use API keys (to restrict API access)
  • Leverage JWT (JSON Web Token) (to strengthen user authentication)

3.5.2 Data Validation

FastAPI can validate request data by using type hints.
from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class UserRequest(BaseModel):
    name: str
    age: int

@app.post("/api/users")
def create_user(user: UserRequest):
    return {"message": f"{user.name} ({user.age} years old) has been registered"}

Summary

This section explained how to build APIs using Python.
  • Creating a simple API with Flask
  • Creating a high-performance API with FastAPI
  • Integrating databases using SQLAlchemy
  • API security measures (authentication & validation)

4. Deploying a Python API

After developing an API in a local environment, you need to deploy (publish) it to run in the cloud. This section explains how to deploy a Python API to a cloud environment. This section covers:
  • Run the API in a local environment
  • Deploying to a cloud environment
  • Deploying with Heroku
  • Serverless deployment using AWS Lambda
  • API performance optimization

4.1 Running the API in a local environment

Before deploying the API, it’s important to verify its operation in a local environment.

4.1.1 Running a Flask app

To run a Flask app locally, follow these steps.
  1. Save the Flask API code as app.py
  2. Run the following command in a terminal
python app.py
This starts the Flask app at http://127.0.0.1:5000/.

4.1.2 Running a FastAPI app

To run a FastAPI app locally, use the following command.
uvicorn main:app --host 127.0.0.1 --port 8000 --reload
This starts the FastAPI app at http://127.0.0.1:8000/.

4.2 Deploying to a cloud environment

Once local verification is complete, deploy to a cloud environment. Here we introduce common deployment methods.

4.2.1 Deploying with Heroku

Heroku is a cloud platform that makes it easy to deploy Python apps.
Heroku deployment steps
  1. Install the Heroku CLI
  • Install from the official site (https://devcenter.heroku.com/articles/heroku-cli)
  1. Log in to Heroku
   heroku login
  1. Initialize a Git repository
   git init
   heroku create my-python-api
  1. Create required files
  • requirements.txt (list required libraries) flask gunicorn
  • Procfile (for Heroku process management) web: gunicorn app:app
  1. Commit to Git and deploy
   git add .
   git commit -m "Deploy API to Heroku"
   git push heroku main
  1. Check the app’s URL
   heroku open
Your Python API is now published on Heroku.

4.2.2 Serverless deployment using AWS Lambda

Using AWS Lambda, you can deploy an API to the cloud without managing servers.
Steps to deploy FastAPI on AWS Lambda
  1. Install the library for AWS Lambda
   pip install mangum
  1. Create a FastAPI app (main.py)
   from fastapi import FastAPI
   from mangum import Mangum

   app = FastAPI()

   @app.get("/")
   def hello():
       return {"message": "Hello from AWS Lambda"}

   handler = Mangum(app)
  1. Deploy to AWS Lambda
  • Integrate with AWS API Gateway
  • Deploy using the AWS CLI
With AWS Lambda, you can run the API without server management.

4.3 Optimizing API performance

Here are several ways to improve API performance after deployment.

4.3.1 Introducing caching

Introduce caching to speed up API responses.
  • For Flask
  from flask_caching import Cache

  cache = Cache(app, config={'CACHE_TYPE': 'simple'})

  @app.route('/data')
  @cache.cached(timeout=60)  # cache for 60 seconds
  def get_data():
      return {"message": "Cached data"}
  • For FastAPI
  from fastapi.middleware.cors import CORSMiddleware

  app.add_middleware(
      CORSMiddleware,
      allow_origins=["*"],
      allow_credentials=True,
      allow_methods=["*"],
      allow_headers=["*"],
  )

4.3.2 Leveraging asynchronous processing

FastAPI supports asynchronous processing (async), which improves performance.
from fastapi import FastAPI

app = FastAPI()

@app.get("/async")
async def async_endpoint():
    return {"message": "This is an async endpoint"}

4.3.3 Load balancing

When the API receives heavy request load, you can use load balancing to distribute the load.
  • AWS offers Elastic Load Balancer (ELB)
  • Heroku provides Auto Scaling
Using these, you can build a scalable API.

Summary

This section explained how to deploy a Python API to a cloud environment.
  • Local API verification
  • Simple deployment using Heroku
  • Serverless deployment using AWS Lambda
  • API performance optimization (caching, async processing, load balancing)
年収訴求

5. Python API FAQ (Frequently Asked Questions)

We’ve compiled frequently asked questions about developing and using APIs with Python. We’ll explain points of interest for beginners to intermediate users, covering everything from the basic workings of APIs to security and performance improvement methods.

5.1 Free services you can use for Python APIs?

When trying out APIs with Python, there are free API services you can use. Leveraging the services below lets you obtain test data and learn how to use APIs.
Service NameDescriptionAPI Documentation
Random User APICan retrieve random user informationhttps://randomuser.me
OpenWeatherMapCan retrieve weather informationhttps://openweathermap.org/api
JSONPlaceholderRetrieves dummy data (posts, comments, user information, etc.)https://jsonplaceholder.typicode.com

5.2 How do web scraping and APIs differ?

Web scraping and APIs are both methods for obtaining external data, but they differ fundamentally.
ItemWeb ScrapingAPI
MethodParse HTML of web pages to extract dataSend requests to a server and retrieve structured data
SpeedSlow (requires page load)Fast (retrieved directly from database)
StabilityHigh chance of breaking due to website changesGenerally stable and usable
Usage LimitsExcessive access may violate terms of serviceData is officially provided, so it’s safe
Conclusion: If possible, using an API is more efficient and safer than web scraping.

5.3 How to manage API keys?

Many APIs use API keys (API Key) for access control. Here are key points for handling API keys securely.

5.3.1 Store API keys in environment variables

Writing API keys directly in Python code is dangerous. Instead, managing them via environment variables is recommended. Setup>
export API_KEY="your-secret-api-key"
Retrieve in Python code:
import os

api_key = os.getenv("API_KEY")
print(f"API Key: {api_key}")

5.3.2 Using a .env file

Using a .env file makes it easy to manage environment variables.
    1. Create a .env file:
API_KEY=your-secret-api-key
  1. Use dotenv in Python:
   pip install python-dotenv
  1. Load the .env file:
   from dotenv import load_dotenv
   import os

   load_dotenv()
   api_key = os.getenv(" print(f"API Key: {api_key}")

5.4 Framework comparison when building APIs with Python

When developing APIs with Python, the main choices are Flask and FastAPI. Compare their characteristics to choose the framework that best fits your project.
>PerformanceSlowerynchronous)manually
ItemFlaskFastAPI
Design PhilosophySimple and lightweightFast and leverages type hints
Type CheckingNone (must be done manually)Available (uses Python type hints)
API Documentation GenerationAutomatically generated (Swagger UI, ReDoc)
Recommended Use CasesSmall-scale APIs, learningHigh-performance APIs, production environments
Conclusion:
  • Flask for beginners or small APIs
  • FastAPI for high‑performance APIs or production

5.5 How to improve API performance?

There are several optimization techniques to improve API response speed.

5.5.1 Implement caching

Caching API responses reduces server load and speeds up performance.
  • Flask
      from flask_caching import Cache
    
      cache = Cache(app, config={'CACHE_TYPE': 'simple'})
    
      @app.route('/data')
      @cache.cached(timeout=60)  # cache for 60 seconds
      def get_data():
          return {"message": "Cached data"}
    • FastAPI
      from fastapi.middleware.cors import CORSMiddleware
    
      app.add_middleware(
          CORSMiddleware,
          allow_origins=["*"],
          allow_credentials=True,
          allow_methods=["*"],
          allow_headers=["*"],
      )

    5.5.2 Leverage asynchronous processing

    In FastAPI, using asynchronous processing (async) improves performance.
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/async")
    async def async_endpoint():
        return {"message": "This is an async endpoint"}

    5.5.3 Load balancing

    When API traffic increases, you can leverage load balancing.
    • AWS Elastic Load Balancer (ELB)
    • Heroku Auto Scaling
    • Nginx reverse proxy

    Summary

    This section explained the frequently asked questions about Python API development.
    • Free API services
    • Differences between web scraping and APIs
    • Secure API key management
    • Flask vs FastAPI comparison
    • API performance optimization
    By applying this knowledge, you can develop and operate APIs that are safer and more efficient. Give Python API development a try!
 
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール