Canbi Pharma Tech Limited

How to create an API in Python?

May 26, 2025

Hey there! I'm part of an APIs supplier team, and today I'm super stoked to share with you how to create an API in Python. It's a pretty cool process, and I'll break it down step by step.

Why Python for API Creation?

First off, you might be wondering why Python is such a great choice for making APIs. Well, Python is known for its simplicity and readability. Its syntax is easy to understand, even if you're new to programming. Plus, there are tons of libraries available that can make API development a breeze.

One of the most popular libraries for creating APIs in Python is Flask. Flask is a lightweight web framework that allows you to quickly build web applications, including APIs. It's great for beginners because it has a simple and intuitive way of handling requests and responses.

Another awesome library is Django REST framework. Django is a more full - fledged web framework, and its REST framework is specifically designed for building RESTful APIs. It comes with a lot of built - in features like authentication, serialization, and pagination.

Setting Up Your Environment

Before you start creating your API, you need to set up your development environment. The first thing you'll need is Python installed on your machine. You can download the latest version of Python from the official Python website.

Once you have Python installed, you'll want to create a virtual environment. A virtual environment is like a sandbox for your Python projects. It allows you to isolate your project's dependencies from other projects on your machine.

To create a virtual environment, open your terminal and run the following command:

202189-78-4 Bilastine1903008-80-9 Lazertinib
python -m venv my_api_env

This will create a new virtual environment named my_api_env. To activate the virtual environment, run:

  • On Windows:
my_api_env\Scripts\activate
  • On macOS and Linux:
source my_api_env/bin/activate

Installing Necessary Libraries

After activating your virtual environment, it's time to install the libraries you'll need. If you're going with Flask, you can install it using pip, which is the package installer for Python. Run the following command in your terminal:

pip install flask

If you're using Django REST framework, you'll need to install Django first and then the REST framework. Here are the commands:

pip install django
pip install djangorestframework

Creating a Simple API with Flask

Let's start with a simple example of creating an API using Flask. Open your favorite text editor and create a new Python file, let's call it app.py.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify({"message": "Hello, World!"})

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

In this code, we first import the Flask class and the jsonify function from the flask library. We create an instance of the Flask class and define a route using the @app.route decorator. When a user makes a request to the root URL (/), the hello_world function is called, which returns a JSON response.

To run the Flask application, open your terminal, navigate to the directory where your app.py file is located, and run:

python app.py

Now, if you open your web browser and go to http://127.0.0.1:5000/, you should see a JSON response with the message "Hello, World!".

Creating a More Complex API

Let's say you want to create an API that returns information about some APIs we supply. For example, we have APIs for different chemical compounds like 1903008 - 80 - 9 Lazertinib, 1234627 - 85 - 0 Siponimod Hemifumarate, and 202189 - 78 - 4 Bilastine.

from flask import Flask, jsonify

app = Flask(__name__)

apis = [
    {
        "name": "1903008 - 80 - 9 Lazertinib",
        "description": "An API for Lazertinib",
        "url": "/apis/1903008-80-9-lazertinib.html"
    },
    {
        "name": "1234627 - 85 - 0 Siponimod Hemifumarate",
        "description": "An API for Siponimod Hemifumarate",
        "url": "/apis/1234627-85-0-siponimod-hemifumarate.html"
    },
    {
        "name": "202189 - 78 - 4 Bilastine",
        "description": "An API for Bilastine",
        "url": "/apis/202189-78-4-bilastine.html"
    }
]

@app.route('/apis', methods=['GET'])
def get_apis():
    return jsonify(apis)

@app.route('/apis/<string:name>', methods=['GET'])
def get_api(name):
    api = next((api for api in apis if api["name"] == name), None)
    if api:
        return jsonify(api)
    return jsonify({"message": "API not found"}), 404

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

In this code, we create a list of dictionaries called apis that contains information about the APIs we supply. We define two routes: one to get all the APIs (/apis) and another to get a specific API by its name (/apis/<string:name>).

Handling API Requests

APIs can handle different types of requests, such as GET, POST, PUT, and DELETE. In the previous example, we only handled GET requests. Let's see how we can handle a POST request to add a new API to our list.

from flask import Flask, jsonify, request

app = Flask(__name__)

apis = [
    {
        "name": "1903008 - 80 - 9 Lazertinib",
        "description": "An API for Lazertinib",
        "url": "/apis/1903008-80-9-lazertinib.html"
    },
    {
        "name": "1234627 - 85 - 0 Siponimod Hemifumarate",
        "description": "An API for Siponimod Hemifumarate",
        "url": "/apis/1234627-85-0-siponimod-hemifumarate.html"
    },
    {
        "name": "202189 - 78 - 4 Bilastine",
        "description": "An API for Bilastine",
        "url": "/apis/202189-78-4-bilastine.html"
    }
]

@app.route('/apis', methods=['GET'])
def get_apis():
    return jsonify(apis)

@app.route('/apis/<string:name>', methods=['GET'])
def get_api(name):
    api = next((api for api in apis if api["name"] == name), None)
    if api:
        return jsonify(api)
    return jsonify({"message": "API not found"}), 404

@app.route('/apis', methods=['POST'])
def add_api():
    new_api = request.get_json()
    apis.append(new_api)
    return jsonify(new_api), 201

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

In this updated code, we added a new route /apis with the POST method. When a client sends a POST request to this route with a JSON payload containing information about a new API, the add_api function is called, which adds the new API to the apis list and returns the newly added API with a status code of 201 (created).

Testing Your API

Testing your API is super important to make sure it works as expected. You can use tools like Postman to send requests to your API and check the responses.

  • Open Postman and create a new request.
  • Set the request method (GET, POST, etc.) and the URL of your API.
  • If it's a POST or PUT request, you can set the request body to JSON and enter the data you want to send.
  • Click the "Send" button, and Postman will show you the response from your API.

Conclusion

Creating an API in Python is a fun and rewarding process. Whether you're using Flask for a quick and simple API or Django REST framework for a more feature - rich one, Python has the tools you need.

If you're interested in our APIs or want to start your own API project, feel free to reach out for a procurement discussion. We're here to help you get the best APIs for your needs.

References

  • Flask official documentation
  • Django REST framework official documentation
  • Python official documentation
goTop