This blog covers making a Django REST API with search feature and integrating it with a Flutter application.
Why a REST API search?
It was a frustrating task to make a search feature inside a flutter application, given the search target was a collection in firebase. Imagine that collection growing and stacking on top of each other to make a list of collections that you need to search through. For example, you are making a social media service for your next big startup that is gonna revolutionize the human lifestyle. But wait, you are sitting there, trying to figure out, how are you gonna make a user search for the girl he was in his class with? He will probably search for the school name, city name, first name, last name or maybe the phone number he got access to from a shady but distant friend in class. Okay, got the logic, but HOW?
We’ve all been through the basics of Linear Search and Binary Search. Fairly basic approach of iterating over a list of items in a fancy way and locating its index. Done. But how do we search through a set of documents inside a collection. One of the YouTubers, Raja Yogan made an excellent video on how to implement instant search using flutter and firebase here.
If you go through the code and see, it is fairly ‘simple’ for a simple search. What happens when the database scales? Are you gonna redundantly write code for different database tables? No. This is one of the reasons I stopped using firebase for bigger projects and switched to writing code for a custom backend. More on that topic later.
API’s allow you to dynamically search through databases quickly and find custom patterns instead of hard coded expressions. Too much? Well wait, will show you guys how to make one yourself in a few minutes.
Setting up the Django Project
Ah, the most mundane task of all. Setting up the Django template project. I’m skipping the parts of installing Python 3.7 and Django 2.2, because if you made it to this blog, it means you have some intermediate understanding of both Django and flutter.
Let’s focus on creating the app inside your template project.
python manage.py startapp search
This will create a boilerpate Django app inside your project. Hurray?
Lets create a model, which will basically translate to a SQL database behind the scenes.
Bam 💥 We are done with making the database.
Run the migration commands and create the super user to access the web admin panel. On accessing the localhost:8000/admin url you should see something like this, given you registered the models in admin.py
Great, now go ahead and add some amazing Food Items and Categories for the former to fall under.
Now the most gruesome part, making the API.
We are going to use DRF (Django Rest Framework) which makes life a lot easier by handling some of the burden we carry all day long.
Be generous and add ‘rest_framework’ to your settings.py
We need to work on three more files, views.py, serializers.py and urls.py. Writing the serializer part is simpler, so lets do that first.
Now comes the view part. Writing a view that enables search filter. A simple view first.
DRF has inbuilt search functionality and database features which allows you to do scalable searching.
Inside your app’s urls.py, add the following:
urlpatterns = [
Open your browser and go to this url localhost:8000/api/foods/
The FoodAPIView in our views.py file enables us to see the data and make api requests to the specified url.
Adding the Search Feature
The Django REST framework has some inbuilt utilities that allow you to implement search easily. Though underneath it also uses i_contains in some cases, it is fast, scalable and easy to implement ;)
Add the following line inside the class FoodAPIView.
search_fields = [‘name’, ‘price’]
On doing so the class would look something like this
We are adding the search_field in API view to specify which columns should the service look for when searching for a query.
Should we now test the search query?
This should return the search results that match the query.
So it works. WOW! Not a big deal really. This was the easy part. Now we need to integrate it with the mobile app.
The easy part? Nah this is heavily inspired by what I saw in Raja Yogan’s code.
Well, this code is really modular and you can find the entire code for reference here.
I guess setting up a sample flutter app wont be an issue and that is the reason I’m skipping the utterly difficult task 😂😂
Let’s write the main.dart file first.
This is how I usually kickstart the app. Dividing the app into small components.
Now let’s code up the search page.
On running this much of the app, we should see something like this.
Without hosting the Django app in a cloud service like AWS or GCP, we need to call the API’s. To do so first we need to connect both the devices [the computer that you are using and the phone that you are running the app on] to the same network.
You need to find the IP address your devices are connected to.
Use ifconfig for Ubuntu, ip addr in Arch and ifconfig in windows to get the IP address.
Reconfiguring the Django Server
As of now, the server was running on localhost:8000/
Our app running on the phone cannot access it. Once we have the ip in hand we need to change a line in settings.py. Replace ALLOWED_HOSTS inside the Django settings.py file with this.
ALLOWED_HOSTS = ['192.168.43.129', 'localhost', '127.0.0.1']
Now turn off the Django server, and restart it with the following command.
python manage.py runserver 0.0.0.0:8000
This will allow you to access your django api in the following URL
The IP must be different in your case.
Great, we have written a great amount of code by now. Time to write the functioning.
Here we have a static function aptly named searchDjangoApi which returns a Future<String>. The URL is the one that we just started accessing our django app at. We are getting the ‘query’ parameter from the UI class and passing it to the function here. Which is then passed as the URL search parameter. The http.Response object helps us retrieve the data that we expect to have. Once we have the response, we return its body.
Woah! Done. Now run your flutter app and the django server.
Let’s see what we get when we search for ‘tan’
That’s it. There is our flutter and django code working together to make this world a better place. Dynamic search is also there, but I’m keeping it out of the scope of this blog. Peace.
If you need the code, just visit my GitHub profile here.
I am a noob programmer and this entire code structure was figured out by me and a few fellow programmers.
Tada, keep searching for the truth and keep filtering ❤️