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.
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?”
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:
To follow along, you’ll need:
If you don't have Python 3.6 or higher installed, follow these steps:
Follow the installation instructions to complete the setup.
Open your command line interface:
This should display the installed Python version, confirming a successful installation.
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:
Use the same command line interface (CLI) you used for verifying the Python installation.
Run the following command in your CLI to install FastAPI:
pip install fastapi
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.
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.
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.
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()
@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.
The core components of this API include:
/
).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:
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.
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.
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. 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 http://localhost:8000/get-message
.
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 supports asynchronous programming 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.
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.
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.
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.
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.
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.
static_string
, to hold the text that our API will manage./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./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./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}
static_string
. For example, sending " world!" to /add
when the string contains "Hello" results in "Hello world!"
.static_string
with the new input. E.g., from "Hello world!" to "Goodbye" becomes "Goodbye"
.static_string
, resetting it to an empty string.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:
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.
Once you're comfortable with these basic operations, here are a few ways to expand your knowledge: