A Detail Guide About How To Build An API In Python: Understanding What Is FastAPI?

Table of Contents

How to build an API in Python?

An API (Application Programming Interface) acts as a bridge, enabling communication between two different computer systems. Imagine you’re using a mobile weather app that offers real-time updates on the weather. The app itself doesn’t generate weather data but relies on external sources to provide accurate and timely information.

When you open the app and check the current weather for your location, the app interacts with an external weather service through an API. This weather service, typically managed by a meteorological organization or a data provider, delivers real-time weather information. Here’s how it works: the app sends a request to the API with your location details. The API processes this request and retrieves weather data—like temperature, humidity, wind speed, and forecasts—from the external service.

Once the data is fetched to build an API in Python, it’s sent back to your phone, and the app presents it in a clear, readable format. This entire process happens in the background, with the API acting as the intermediary, allowing the app to access and display the weather data without the user noticing any of the technical steps.

APIs can be built using various programming languages, but today we’ll focus on how to build an API in Python. If you have a basic understanding of HTTP and the fundamentals of APIs, you’re ready to get started. Let’s dive in and explore how to build a Python-based API.

Getting Started to Build An API In Python

FastAPI is a high-performance web framework for Python, created by Sebastián Ramírez in 2018.

Creating an API in Python can be done in multiple ways, but for beginners, I'll guide you through a simple and efficient approach using FastAPI. Let’s start with the basics of “What is FastAPI?”

What is FastAPI?

FastAPI is a high-performance web framework for Python, created by Sebastián Ramírez in 2018. It is well-known for its speed, asynchronous support, and ease of use. By utilizing Python 3.6+ type hints, FastAPI automatically handles data validation and generates comprehensive API documentation. It’s perfect for building fast, scalable APIs and excels in handling applications that require high concurrency.

Some key features of FastAPI include:

Prerequisites

To follow along, you’ll need:

Installing Python 3.6+

If you don't have Python 3.6 or higher installed, follow these steps:

1. Download Python

2. Install Python

Follow the installation instructions to complete the setup.

3. Verify the installation

Open your command line interface:

This should display the installed Python version, confirming a successful installation.

Installing FastAPI and Uvicorn

Once Python is installed, the next step is to set up FastAPI and Uvicorn. FastAPI will be the framework for building the API, while Uvicorn will serve as the ASGI server that runs the application. Here’s how to install both:

Step 1: Open your Command Line Interface

Use the same command line interface (CLI) you used for verifying the Python installation.

Step 2: Install FastAPI

Run the following command in your CLI to install FastAPI:

pip install fastapi

Step 3: Install Uvicorn

Next, install Uvicorn by running this command:

pip install uvicorn[standard]

The [standard] flag ensures that you install additional, commonly-used dependencies, optimizing Uvicorn for most scenarios.

Creating Your First API Endpoint

With FastAPI and Uvicorn installed,time to create your first API

With FastAPI and Uvicorn installed, it’s time to create your first API. This will involve writing a Python script to define your application and its corresponding endpoints.

Step 1: Create a Python File

Create a new Python file (e.g., main.py) where you will write the code for your API. This file will act as the foundation of your application, outlining its structure, endpoints, and functionality.

Step 2: Set Up the FastAPI Application

In this file, you will initialise a FastAPI instance and define an API endpoint. Here’s a basic example of how to do this:

# Import the FastAPI class

from fastapi import FastAPI

# Create an instance of the FastAPI application

app = FastAPI()

# Define a basic API endpoint

@app.get("/")
def read_root():
return {"message": "Welcome to your first FastAPI app!"}

In this example:

app = FastAPI() creates an instance of the FastAPI app.

The @app.get("/") decorator defines an endpoint that responds to a GET request at the root URL (/). When accessed, it returns a JSON response with a simple message.

Step 3: Define API Elements

The core components of this API include:

Running Your API with Uvicorn

Once your Python file is ready, you can run your API using Uvicorn. In your CLI, navigate to the directory where your main.py file is located and run the following command:

uvicorn main:app –reload

Here:

main refers to the Python file (main.py).

app refers to the FastAPI instance inside that file.

The --reload flag allows the server to automatically reload if you make changes to the code.

Your API is live! You can access it by visiting http://127.0.0.1:8000 in your browser. The interactive API documentation will be available at http://127.0.0.1:8000/docs.

Let’s break down the code step by step:

Passing a Parameter

In the previous example, we built a simple API that returned a static message. This involved minimal code, demonstrating how to define the HTTP method (GET), set up the endpoint ("/get-message"), and create a function that responds to the API call.

However, APIs often need to handle dynamic data by accepting parameters. With FastAPI, we can pass arguments to our API functions and specify their data types, which ensures that the API only receives valid inputs. This type of data validation is a key feature of FastAPI, offering an advantage over frameworks like Flask, which don’t include strict type-checking by default.

When a parameter is passed to a FastAPI function, the framework automatically checks if the data type matches the one defined in the function. If the type doesn’t match, FastAPI will reject the request and return an appropriate error response. This type of robust validation is crucial for ensuring that the API functions correctly and securely.

In the next example, we’ll see how to pass parameters and leverage FastAPI’s automatic validation for cleaner and more efficient API development.

Introducing Parameters to Our API

Now that we’ve updated our API to require a parameter, the requests must include this parameter for the API to function properly. Previously, accessing the API was as simple as navigating to http://127.0.0.1:8000/get-message. However, with the addition of the name parameter, the request URL needs to be adjusted.

For example, if we want to pass the name "Stefan," the URL would now be:

http://127.0.0.1:8000/get-message?name=Stefan.

In this case, FastAPI automatically extracts the value of the name parameter from the request and uses it in the response. This demonstrates how easily parameters can be passed to API endpoints, enhancing the API's flexibility and usefulness.

Creating POST, PUT, and DELETE Endpoints

Now let’s explore how to create POST, PUT, and DELETE endpoints. These methods allow us to modify a resource—in this case, a simple static string. To keep things straightforward, we won’t be working with a database or complex data structures. Instead, we’ll use a string variable to demonstrate how each method works.

Let’s walk through the steps to set up these endpoints.

Working with a Global Variable and API Endpoints

In this section, we'll explore how to handle basic operations on a string using different HTTP methods in FastAPI. We’ll start with a global variable that stores the text, and we’ll build several API endpoints to manipulate this string.

Here’s how these operations are set up in FastAPI:

from fastapi import FastAPI

        app = FastAPI()
        static_string = "Initial text"
        
        @app.post("/add")
        async def add_text(text: str):
            global static_string
            static_string += text
            return {"updated_text": static_string}
        
        @app.put("/change")
        async def change_text(new_text: str):
            global static_string
            static_string = new_text
            return {"new_text": static_string}
        
        @app.delete("/remove")
        async def remove_text():
            global static_string
            static_string = ""
            return {"message": "Text removed", "current_text": static_string}
        

Explanation of Each Endpoint:

Real-World Application

While this example uses a simple string, in real-world scenarios, these endpoints would handle more complex data, such as user profiles, database entries, or files. Additionally, you'd incorporate features like:

Conclusion

Creating APIs with FastAPI combines Python’s simplicity with the power of modern, asynchronous web frameworks. In this example, we demonstrated how to perform basic operations using POST, PUT, and DELETE requests. These requests allow us to add, update, or remove text from a string, showcasing how simple and efficient it is to manage API endpoints with FastAPI.

FastAPI’s built-in features, such as automatic validation, support for asynchronous operations, and easy-to-read documentation, make it a fantastic choice for developers of all skill levels.

Next Steps

Once you're comfortable with these basic operations, here are a few ways to expand your knowledge: