Django Search + Flutter š
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 = [
path('foods/', views.FoodAPIView.as_view()),
]
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?
localhost:8000/api/foods?search=Tando
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.
UI First
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
http://192.168.43.***:8000/api/foods/
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.
You can check Nikhileshās, Nikhilās and Dhruvās work in their GitHub profile.
Tada, keep searching for the truth and keep filtering ā¤ļø