Create an API with Python in Just 10 Minutes: A Step-by-Step Guide with Flask and Postman

Create an API with Python in Just 10 Minutes: A Step-by-Step Guide with Flask and Postman

Introduction:

It was 2 AM, and I was sitting in front of my laptop, feeling frustrated. My boss had asked me to connect our internal app to a third-party service by the end of the week. I had no idea where to start, and the idea of creating an API felt like learning rocket science. I scoured forums, watched countless tutorials, and still couldn’t quite grasp it.

That was until I stumbled upon Flask, a lightweight Python framework that made everything click. In just a few hours, I went from knowing nothing about APIs to creating one that worked seamlessly. The best part? I realized it wasn’t as difficult as I thought.

If you’re anything like I was, API development might seem daunting, but trust me, it’s not. In this guide, I’ll show you how to create an API with Python and Flask in just 10 minutes. Whether you’re building your first project or adding API skills to your toolkit, this step-by-step guide will get you up and running fast — and we’ll use Postman to make sure everything works smoothly. Let’s dive in!

Why Flask?

Flask is a lightweight web framework for Python that makes building APIs quick and straightforward. It’s highly flexible, allowing developers to scale from simple APIs to more complex ones without much overhead.

What You’ll Need

Before we dive in, make sure you have the following:

  • Python is installed on your machine.
  • A virtual environment for your project (optional but recommended).
  • Postman installed for testing (you can download it here).

Step 1: Setting Up Flask

First, let’s set up Flask. Open your terminal or command prompt and create a virtual environment (optional but useful for keeping your dependencies organized).

# Create a virtual environment
python -m venv venv

# Activate the virtual environment (Linux/Mac)
source venv/bin/activate

# Activate the virtual environment (Windows)
venv\Scripts\activate        

Now, install Flask by running the following command:

pip install Flask        

Once Flask is installed, let’s create a file called main.py where we will build our API.

Step 2: Creating the Basic API

In your main.py file, start by importing the necessary libraries:

from flask import Flask, jsonify, request

app = Flask(__name__)        

Here, we create an instance of Flask called app which will act as the server for our API.

Next, we’ll define our first route. This route will respond when a user visits the root URL (/).

@app.route('/')
def home():
    return "Welcome to my API!"        

At this point, we’ve created a very simple API that returns a text message. To run it, add the following lines at the bottom of your file:

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

Save the file, and in your terminal, run the following command:

python main.py        

You should see output indicating that the server is running on https://127.0.0.1:5000/. Open this URL in your browser, and you should see the message: "Welcome to my API!"


Step 3: Adding GET and POST Endpoints

Now, let’s make our API more useful by adding two endpoints: one for retrieving user data (GET) and another for creating new users (POST).

GET Request: Fetching User Data

We’ll start by creating a route that returns user information. This will mimic a simple database query.

@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    users = {
        1: {"name": "Kevin", "phone": "555-1234"},
        2: {"name": "Javier", "phone": "555-5678"}
    }
    user = users.get(user_id, None)
    
    if user:
        return jsonify(user), 200
    else:
        return jsonify({"error": "User not found"}), 404        

This route accepts a user_id as part of the URL and returns user details if the ID exists. If the ID is not found, the API returns a 404 error.

POST Request: Creating a New User

Now, let’s create a route to add a new user via a POST request. The user data will be sent in JSON format.

@app.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    new_user = {
        "name": data.get('name'),
        "phone": data.get('phone')
    }
    return jsonify(new_user), 201        

In this endpoint, we accept user data in JSON format and return it with a 201 status code, which indicates that a resource has been successfully created.


Step 4: Testing with Postman

Now that we have our API running, it’s time to test it using Postman.

  1. Open Postman and create a new request.
  2. Testing GET request:

  • Set the method to GET.
  • Enter the URL: https://127.0.0.1:5000/users/1.
  • Click Send, and you should see the details for user 1.

You will get the initial users set up in the code before

3. Testing POST request:

  • Set the method to POST.
  • Enter the URL: https://127.0.0.1:5000/users.
  • Go to the Body tab, select raw and JSON.
  • Enter the following JSON data

{
  "name": "Carlos",
  "phone": "555-4321"
}        

Conclusion

In just 10 minutes, you’ve built a fully functional API using Python and Flask. You’ve learned how to:

  • Set up a basic API.
  • Create GET and POST endpoints.
  • Test your API using Postman.

This is just the beginning! From here, you can expand your API to connect to a database, add authentication, or even deploy it to a cloud service like Heroku. The possibilities are endless, and now that you have the fundamentals down, you can dive deeper into API development.

If you found this guide helpful, don’t forget to like and share it with others who are starting their journey into API development. Stay tuned for more tutorials on how to enhance your APIs with security, database integration, and more!

Follow me on Linkedin https://www.dhirubhai.net/in/kevin-meneses-897a28127/

Subscribe to the Data Pulse Newsletter https://www.dhirubhai.net/newsletters/datapulse-python-finance-7208914833608478720

Join my Patreon Community https://patreon.com/user?u=29567141&utm_medium=unknown&utm_source=join_link&utm_campaign=creatorshare_creator&utm_content=copyLink

要查看或添加评论,请登录

社区洞察

其他会员也浏览了