API Development and Monitoring with FastAPI and Apitally
Tags: python, fastapi, apitally, monitoring
Published: 2024-06-25 14:05:27

In today's digital world, creating and keeping up effective APIs is really important for the success of web applications.

FastAPI has become a favorite among developers because of its high speed and easy-to-use design when building APIs.

Working together with FastAPI is Apitally, a tool that makes monitoring and analyzing APIs easier. Apitally gives detailed information about API usage, performance, and health without risking data privacy or application speed.

This combination of FastAPI and Apitally helps developers to create, use, and monitor APIs more efficiently and confidently, making sure they work well and reliably in real-world situations.

---

## Introduction to FastAPI

![FastAPI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zc6wfukytbc2dl16cz2b.png)

FastAPI is a quick, and efficient web framework used for creating APIs with Python 3.7+. It's built on standard Python type hints and is designed to be both easy to use and strong. 

FastAPI focuses a lot on performance and making developers more productive. 

Here are some of its features:
- **Speed**: FastAPI is as fast as NodeJS and Go because it can do multiple tasks at once (asynchronous). This is possible because of Starlette and Pydantic.
- **Ease of Use**: FastAPI is simple and easy to understand, making it quick to learn and use.
- **Documentation**: FastAPI automatically creates interactive API documentation for you.
- **Validation**: FastAPI automatically checks the data you enter based on the types you've set. This makes sure that only the correct data is used.

---

## What is Apitally?
![ApiTally](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mcal7ket7syb2n1a6xp3.png)

Apitally is a simple and budget-friendly tool made for keeping an eye on REST APIs. It gives you detailed information and analytics while keeping your data private and making sure everything runs smoothly. 

Apitally works with many web frameworks, including FastAPI, and helps developers understand how their API is being used, check its performance, and get notified about any problems.

Here are some of the key features of Apitally:
- **API Traffic Monitoring**: Apitally keeps track of API requests, errors, the size of the data being sent, and how long it takes to get a response.
- **Uptime Monitoring & Alerting**: It checks if your API is running and sends you an immediate alert if there are any issues.
- **Privacy**: Apitally doesn't collect any sensitive data and doesn't affect how well your API works.
- **Ease of Integration**: It's easy to add Apitally to your project with just a few lines of code. You don't need to change how your API traffic works or install any extra software.

---

## Adding Apitally to a FastAPI App
To use Apitally with your FastAPI app, you need to install the Apitally client and add it to your FastAPI app as middleware. 

Here's a quick guide. First, install it with pip:

```
pip install apitally[fastapi]
```
_This assumes you have already installed FastAPI, of course._

Then add it as a middleware to a FastAPI app:

```
from fastapi import FastAPI
from apitally.fastapi import ApitallyMiddleware

app = FastAPI()

app.add_middleware(
    ApitallyMiddleware,
    client_id="your-client-id",
    env="dev",  # Change to "prod" for production environment
)
```

And that is it. That is all you need to do for your APIs to immediately be moniterd by Apitally.

### Identifying Consumers
Let's now take a look at a more complete example. 

As you can see from the previous code snippet you will need an Apitally ClientID key. Full setup instructions here.

In order to understand and analyze who is using your API in Apitally, you need to know where the API requests are coming from. This is called identifying the API consumers.

The way you identify the API consumers depends on your specific application and how you want to use it. If your application already has a way to confirm the identity of its users (for example, by requiring them to log in), it would make sense to use that confirmed identity (like the username) as the identifier for the API consumer. This way, you can see which user is making which API requests.

For this example, we will identify the user by it's IP address:

```
from fastapi import FastAPI, Request
from apitally.fastapi import ApitallyMiddleware

# Create FastAPI app
app = FastAPI()

# Add Apitally middleware
app.add_middleware(
    ApitallyMiddleware,
    client_id="<your_client_id>",
    env="dev",  # Change to "prod" for production environment
)


# Root endpoint
@app.get("/")
async def root(request: Request):
    request.state.consumer_identifier = request.client.host
    return {"message": "Hello World"}


# Hello endpoint
@app.get("/hello/{name}")
async def say_hello(request: Request, name: str):
    request.state.consumer_identifier = request.client.host
    return {"message": f"Hello {name}"}
```

Here's a breakdown of what the code does:
- Import necessary modules: The code imports the FastAPI and Request modules from the fastapi library and the ApitallyMiddleware module from the apitally.fastapi library.
- Create a FastAPI app: A new FastAPI application is created and stored in the variable app.
- Add Apitally middleware: The Apitally middleware is added to the FastAPI app. This middleware helps track and monitor API usage. The client_id is set to a specific value, and the env is set to "dev" for a development environment.
- Define the root endpoint: A new endpoint is defined for the root URL ("/") of the application. When this URL is accessed, it sets the consumer_identifier to the hostname of the client making the request.
- Define a "hello" endpoint: Another endpoint is defined that takes a parameter name. When this URL is accessed with a name (for example, "/hello/John"), it sets the consumer_identifier to the hostname of the client making the request.

Of course, when using in a production environment you should be aware of exposing the client id and should place it in an environment variable.

Let's now see what happens you call the endpoints a couple of times:

![ApiTally Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/al8f7gyxy90dqomkerfj.png)

Here you can see the total requests, response time and error rate.

Going into the detail of a endpoint request:

![ApiTally Endpoint Request Log](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1x36oq14b6giw4fpycnl.png)

Here you can see the details of the request for that endpoint, as well as the identified consumer, in this case 127.0.0.1.

---

## Benefits of Using Apitally
Here are some of the benefits of using Apitally to monitor your APIs:
- **Better Monitoring**: Apitally gives you real-time information about how well your API is performing and how it's being used.
- **No Slowdowns**: Apitally is designed to work in the background, so it won't make your app run slower.
- **Instant Alerts**: Apitally sends you notifications about any problems with your API so you can fix them quickly.
- **Privacy**: Apitally doesn't collect any sensitive data, following the best practices for keeping data private.

---

## Conclusion
By using FastAPI for building web applications and Apitally for monitoring, you get a strong, fast, and safe solution. 

FastAPI is easy to use and quick, while Apitally provides detailed monitoring and cares about privacy. 

This combination makes sure your APIs work well and are dependable, while also giving you the information you need to keep improving your service.