Project
12 min read
November 8, 2024
Building Your First Web API with Flask
Michael Rodriguez
Python Instructor
Building Your First Web API with Flask
Flask is a lightweight and powerful web framework for Python that makes it easy to build web APIs. In this tutorial, we'll create a simple but complete REST API.
Setting Up Flask
First, let's install Flask and set up our basic application structure:
pip install flask
Creating Your First API
Here's how to create a basic Flask API:
from flask import Flask, jsonify, request app = Flask(__name__) # Sample data books = [ {"id": 1, "title": "Python Crash Course", "author": "Eric Matthes"}, {"id": 2, "title": "Automate the Boring Stuff", "author": "Al Sweigart"} ] @app.route('/api/books', methods=['GET']) def get_books(): return jsonify(books) @app.route('/api/books/<int:book_id>', methods=['GET']) def get_book(book_id): book = next((book for book in books if book["id"] == book_id), None) if book: return jsonify(book) return jsonify({"error": "Book not found"}), 404 @app.route('/api/books', methods=['POST']) def create_book(): data = request.get_json() new_book = { "id": len(books) + 1, "title": data["title"], "author": data["author"] } books.append(new_book) return jsonify(new_book), 201 if __name__ == '__main__': app.run(debug=True)
API Endpoints
Our API now supports:
- GET /api/books - Get all books
- GET /api/books/:id - Get a specific book
- POST /api/books - Create a new book
Testing Your API
You can test your API using curl or Postman:
# Get all books curl http://localhost:5000/api/books # Get a specific book curl http://localhost:5000/api/books/1 # Create a new book curl -X POST http://localhost:5000/api/books \ -H "Content-Type: application/json" \ -d '{"title": "Learning Python", "author": "Mark Lutz"}'
Next Steps
This is just the beginning! In future tutorials, we'll cover:
- Database integration with SQLAlchemy
- Authentication and authorization
- API documentation with Swagger
- Deployment to production
Flask makes it easy to start building APIs, and with these foundations, you're ready to create more complex applications.
Ready to Start Learning Python?
Join thousands of students mastering Python with our structured courses
Start Your Journey