Skip to Content
Course content

10.3 Building a Simple API

Building a simple API allows you to create a service that can communicate with other applications or users over HTTP. In Python, one of the most popular frameworks for building APIs is Flask due to its simplicity and flexibility. In this section, we will walk through the process of building a simple API using Flask.

1. Setting Up the Environment

Before you can build an API, you need to install Flask, a lightweight Python web framework. You can install it via pip:

pip install Flask

2. Creating a Basic Flask API

Once Flask is installed, you can start building a simple API by defining routes and handling HTTP requests. Here is an example of a simple API that returns a JSON response.

Example Code:

from flask import Flask, jsonify

app = Flask(__name__)

# Define a route for the API
@app.route('/api/hello', methods=['GET'])
def hello_world():
    return jsonify(message="Hello, World!")

# Start the Flask application
if __name__ == '__main__':
    app.run(debug=True)

Explanation:

  • Flask(__name__): Initializes a new Flask application.
  • @app.route('/api/hello', methods=['GET']): Defines an API endpoint at /api/hello which accepts GET requests.
  • jsonify(message="Hello, World!"): Converts a Python dictionary into a JSON response.
  • app.run(debug=True): Starts the Flask development server with debugging enabled, allowing you to test the API locally.

3. Testing the API Locally

Once the Flask app is running, you can test it by navigating to http://127.0.0.1:5000/api/hello in your web browser or using a tool like curl or Postman.

Example:

curl http://127.0.0.1:5000/api/hello

Expected Output:

{
    "message": "Hello, World!"
}

4. Handling Different HTTP Methods

APIs commonly use various HTTP methods to interact with resources. Flask allows you to handle different HTTP methods like GET, POST, PUT, and DELETE. Below is an example of how to handle a POST request.

Example Code for POST Request:

from flask import Flask, request, jsonify

app = Flask(__name__)

# In-memory storage for demonstration
users = []

@app.route('/api/users', methods=['GET'])
def get_users():
    return jsonify(users)

@app.route('/api/users', methods=['POST'])
def add_user():
    user_data = request.get_json()  # Parse JSON data from the request body
    users.append(user_data)  # Add the user data to the in-memory list
    return jsonify(message="User added successfully"), 201  # Return a success message

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

Explanation:

  • @app.route('/api/users', methods=['GET']): This endpoint will return the list of users stored in the users list.
  • @app.route('/api/users', methods=['POST']): This endpoint allows the user to send data (in JSON format) to add a new user. request.get_json() is used to parse the JSON payload.
  • users.append(user_data): The new user data is added to the users list, which acts as an in-memory database for demonstration purposes.
  • The response for a successful POST request is 201 Created, and a message confirming the action is returned.

5. Handling Query Parameters

Sometimes, API clients send additional parameters in the URL (e.g., /api/users?id=1). You can handle these query parameters using request.args.

Example Code:

@app.route('/api/user', methods=['GET'])
def get_user():
    user_id = request.args.get('id')  # Extract query parameter 'id'
    for user in users:
        if user['id'] == user_id:
            return jsonify(user)
    return jsonify(message="User not found"), 404

Explanation:

  • request.args.get('id'): Extracts the value of the id query parameter from the URL.
  • The API looks for a user with the matching id and returns the user data. If no user is found, it returns a 404 response with a "User not found" message.

6. Error Handling in APIs

Handling errors gracefully is important for APIs. Flask provides a way to handle errors using @app.errorhandler.

Example Code for Error Handling:

@app.errorhandler(404)
def not_found(error):
    return jsonify(message="Resource not found"), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify(message="Internal server error"), 500

Explanation:

  • @app.errorhandler(404): This decorator handles 404 errors, which occur when a route is not found.
  • @app.errorhandler(500): This decorator handles internal server errors (500), which can happen during processing.

7. Returning Different Status Codes

APIs often return different HTTP status codes to indicate the result of the request. For instance, a successful GET request might return a 200 OK, while a failed POST might return a 400 Bad Request.

Example Code:

@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if username == "admin" and password == "password":
        return jsonify(message="Login successful"), 200
    else:
        return jsonify(message="Invalid credentials"), 400

Explanation:

  • If the login credentials are correct, the API returns a 200 OK with a success message.
  • If the credentials are incorrect, the API returns a 400 Bad Request with an error message.

8. Running the API

After writing your code, you can run the API by executing the Python script:

python app.py

This will start the Flask server and expose your API locally at http://127.0.0.1:5000/.

9. Deployment (Optional)

Once your API is working locally, you may want to deploy it to the web. Some popular platforms for deploying Flask APIs are:

  • Heroku: A cloud platform that supports deploying Flask apps with minimal configuration.
  • AWS (Amazon Web Services): Using services like Elastic Beanstalk or EC2 for scalable deployment.
  • DigitalOcean: A cloud provider with simple setup options for Flask apps.

Summary

  • Flask is a lightweight Python framework to build APIs.
  • You can handle various HTTP methods like GET, POST, PUT, and DELETE.
  • Use request.get_json() to parse incoming data and jsonify() to send JSON responses.
  • Flask supports query parameters (request.args.get()) and error handling (@app.errorhandler).
  • HTTP status codes are used to indicate the result of the API request (e.g., 200, 404, 500).

By following these steps, you can easily build and test a simple API in Python using Flask.

Commenting is not enabled on this course.