# FastAPI + MongoDB pagination example!

In this tutorial, we will explore how to implement pagination in FastAPI using a MongoDB database. We will create a simple REST API that returns a list of items from a MongoDB collection and paginates the results.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1679810253221/b5fcc545-989b-4af7-9772-38c6c2cd6a94.jpeg align="center")

### Step 1:

Set up the Database

First, you will need to install MongoDB and create a collection to work with. For this tutorial, we will create a collection called "items" with the following schema:

```json
{
  "_id": ObjectId("5f5d1b5cf2e5fe712f0c1b5a"),
  "name": "Item 1",
  "description": "This is item 1"
}
```

### Step 2:

Install Dependencies

Next, install the necessary dependencies. You will need to install the following libraries:

```bash
pip install fastapi
pip install uvicorn
pip install pymongo
```

### Step 3:

Create a FastAPI app

Once you have installed the dependencies, create a new file called "[main.py](http://main.py)" and import the necessary libraries:

```python
from fastapi import FastAPI, HTTPException
from pymongo import MongoClient
from bson.objectid import ObjectId
```

Next, create a FastAPI app instance:

```python
app = FastAPI()
```

### Step 4:

Define the Pagination Endpoint

Now that the app is set up, define the pagination endpoint:

```python
@app.get("/items/")
async def get_items(page: int = 1, limit: int = 10):
    client = MongoClient("mongodb://localhost:27017/")
    db = client["mydatabase"]
    items = db["items"].find().skip((page - 1) * limit).limit(limit)
    return list(items)
```

This endpoint takes in two query parameters: `page` and `limit`. `page` specifies the page number and defaults to 1, while `limit` specifies the number of items per page and defaults to 10. The endpoint uses the `skip()` and `limit()` methods of the MongoDB `find()` method to paginate the results.

### Step 5:

Start the Server

Finally, start the server using the "uvicorn" library:

```bash
uvicorn main:app --reload
```

This will start the server on [localhost:8000](http://localhost:8000). You can now test the pagination endpoint using a tool like Postman. To get the second page of results, for example, you can make a GET request to [`http://localhost:8000/items?page=2`](http://localhost:8000/items?page=2).

### Conclusion

In this tutorial, we have explored how to implement pagination in FastAPI using a MongoDB database. By using MongoDB `skip()` and `limit()` methods, we were able to paginate the results and return a subset of the items. FastAPI makes it easy to create a robust REST API in Python, and with MongoDB, we can store and retrieve data quickly and efficiently.

I hope this helps, you!!

**More such articles:**

[https://medium.com/techwasti](Link)

[https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA](Link)

[https://www.techwasti.com/](Link)

\==========================\*\*=========================

**If this article adds any value to you then please clap and comment.**

**Let’s connect on** [**Stackoverflow**](http://stackoverflow.com/users/3187349/maheshwar-ligade)**,** [**LinkedIn**](https://in.linkedin.com/in/maheshwar-ligade-14447841)**, &** [**Twitter**](https://twitter.com/MaheshwarLigade)**.**
