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

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

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

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:

  • Asynchronous programming support, ideal for handling multiple tasks simultaneously.
  • Built-in security features like OAuth2 and JWT (JSON Web Tokens) for secure authentication.
  • Auto-generated, interactive API documentation that simplifies development and testing.

Prerequisites

To follow along, you’ll need:

  • Python 3.6+ installed on your machine.
  • The FastAPI library installed.
  • The Uvicorn server installed to run your FastAPI application.

Installing Python 3.6+

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

1. Download Python

  • Visit the official Python website at python.org.
  • Select the latest stable version of Python (3.6 or newer). Opting for the most recent version ensures access to the latest features and security updates.
  • Download the appropriate installer for your operating system (Windows, macOS, or Linux).

2. Install Python

  • Run the downloaded installer.
  • Important: During the installation process, make sure to check the box that says “Add Python to PATH.” This ensures you can run Python from the command line.

Follow the installation instructions to complete the setup.

3. Verify the installation

Open your command line interface:

  • Windows: Command Prompt
  • macOS/Linux: Terminal
  • Type the following command:
  • python –version
  • On some Linux distributions, you may need to use:
  • python3 –version

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, 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:

  • Endpoint: The URL where the API is accessible (in this case, /).
  • HTTP Method: The method used to interact with the API (GET, POST, PUT, DELETE, etc.). Here, we use a GET request.
  • Input Parameters: In this example, no parameters are required, but you can define inputs like query parameters or JSON data.
  • Functionality: The code inside the function performs the desired action. In this case, it returns a message to the user.

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 https://127.0.0.1:8000 in your browser. The interactive API documentation will be available at https://127.0.0.1:8000/docs.

Let’s break down the code step by step:

? from fastapi import FastAPI This line imports the FastAPI class from the fastapi module. FastAPI is a powerful web framework that makes building APIs simple while adhering to OpenAPI standards for RESTful APIs. This framework provides automatic validation, documentation, and other useful features for developers.

? app = FastAPI() Here, we’re creating an instance of the FastAPI class and storing it in a variable named app. This instance is the core of your web application. It manages the lifecycle of the app by handling all incoming requests and sending them to the correct endpoint.

? @app.get("/get-message") This line is known as a route decorator. It tells FastAPI to create a new API endpoint that listens for HTTP GET requests at the /get-message URL path. The @app.get part specifies that this endpoint will respond only to GET requests, but FastAPI can also handle other HTTP methods like POST, PUT, and DELETE with similar decorators. The path "/get-message" defines where this endpoint will be available. For example, if your server is running locally on port 8000, the endpoint can be accessed via the URL https://localhost:8000/get-message.

? async def read_root() This line defines an asynchronous function called read_root. The async keyword signifies that the function is asynchronous, meaning it can handle I/O-bound tasks efficiently without blocking the system. FastAPI is designed to support asynchronous programming, allowing the application to handle many requests concurrently without slowing down.

This function is associated with the /get-message endpoint created earlier. When a client sends a GET request to this URL, FastAPI will trigger this function to process the request.

? return {"Message": "Congrats! This is your first API!"} Inside the read_root function, a Python dictionary is returned: {"Message": "Congrats! This is your first API!"}. FastAPI automatically converts this dictionary into a JSON response. So, when a user or a tool like Postman sends a GET request to the /get-message endpoint, they’ll receive a JSON response with the message: {"Message": "Congrats! This is your first API!"}.

This seamless process between defining functions, handling requests, and returning JSON data showcases the simplicity and power of FastAPI for creating web APIs.

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 https://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: https://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.

  • POST: This method will be used to append new text to the string.
  • PUT: This method will completely replace the existing string with new text.
  • DELETE: This method will remove the string, leaving it empty.

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.

  • Global Variable: We'll use a global variable, static_string, to hold the text that our API will manage.
  • POST Request: The /add endpoint allows clients to append additional text to static_string. When a user sends a string to this endpoint, it will be added to the existing text.
  • PUT Request: The /change endpoint is used to replace the entire static_string with a new value. This is useful when we need to overwrite the existing text completely.
  • DELETE Request: The /remove endpoint deletes the current value of static_string, effectively resetting it.

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:

POST /add: Appends text to static_string. For example, sending " world!" to /add when the string contains "Hello" will result in "Hello world!".

PUT /change: Completely replaces static_string with the new input. For example, changing the string from "Hello world!" to "Goodbye" will result in "Goodbye".

DELETE /remove: Clears the contents of static_string, resetting it to an empty string.

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:

  • Error Handling: Managing unexpected inputs or failures.
  • Validation: Ensuring the data is correct before processing.
  • Database Integration: Persisting and managing data with a database instead of a static variable.

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:

  • Advanced Features: Explore more advanced FastAPI capabilities, such as dependency injection, authentication, and middleware.
  • Asynchronous Programming: Dive deeper into asynchronous programming to optimize your APIs for performance.
  • Database Integration: Learn how to integrate databases (such as PostgreSQL or MongoDB) to manage complex, dynamic data.
  • Testing and Deployment: Practise writing tests for your API endpoints and deploy your application in a production environment using cloud services like AWS or Docker.


Visit us for more information on Optimizory


Md Shakawat Hossain

Software Engineer | Java Native Android | Cross-Platform Solutions | API development

3 周

Awesome guide! FastAPI makes API development smooth and efficient.

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

Optimizory的更多文章

社区洞察

其他会员也浏览了