GraphQL has gained immense popularity in modern app development due to its flexibility in fetching only the required data.
When combined with Flutter, a leading framework for cross-platform development, it can elevate the efficiency and performance of your app.
In this blog, we’ll explore how to Implement GraphQL with HTTP in Flutter for seamless data querying.
What is GraphQL?
GraphQL is an open-source query language developed by Facebook.
Unlike REST APIs, GraphQL provides a more dynamic and efficient approach to interacting with APIs by allowing clients to request only the specific data they need.
This reduces over-fetching or under-fetching of data, making applications more efficient.
Implementation
To begin with GraphQL in Flutter, you need to set up your Flutter project.
Add dependencies: To use HTTP for GraphQL, you’ll need the http
package. Add the following to your pubspec.yaml file:
1 2 3 4 |
dependencies: flutter: sdk: flutter http: ^0.15.0 # Update to the latest version |
Run flutter pub get
to fetch the dependencies.
Understanding GraphQL Basics
GraphQL operates on two main operations:
- Query: Fetch data.
- Mutation: Modify data.
Each operation is structured as a JSON-like query but uses a specific syntax to define what data is needed.
Making a GraphQL Query with HTTP
Here’s how you can implement this in Flutter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import 'dart:convert'; import 'package:http/http.dart' as http; Future<void> fetchUsers() async { const String graphqlEndpoint = 'https://www.example.com/graphql'; const String query = ''' query { users { id name email } } '''; final response = await http.post( Uri.parse(graphqlEndpoint), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'query': query}), ); if (response.statusCode == 200) { final data = jsonDecode(response.body); print(data['data']['users']); } else { throw Exception('Failed to fetch users'); } } |
Replace https://example.com/graphql
with your GraphQL endpoint.
Handling GraphQL Mutations
Mutations allow you to modify data on the server. For example, to create a new user:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Future<void> createUser(String name, String email) async { const String graphqlEndpoint = 'https://example.com/graphql'; const String mutation = ''' mutation(\$name: String!, \$email: String!) { createUser(input: { name: \$name, email: \$email }) { id name email } } '''; final variables = {'name': name, 'email': email}; final response = await http.post( Uri.parse(graphqlEndpoint), headers: {'Content-Type': 'application/json'}, body: jsonEncode({'query': mutation, 'variables': variables}), ); if (response.statusCode == 200) { final data = jsonDecode(response.body); print(data['data']['createUser']); // Access the created user data } else { throw Exception('Failed to create user'); } } |
Error Handling
GraphQL responses often include a errors
field. To handle errors:
1 2 3 4 5 6 7 |
final responseBody = jsonDecode(response.body); if (responseBody['errors'] != null) { print('GraphQL Error: ${responseBody['errors']}'); } else { print('Data: ${responseBody['data']}'); } |
Conclusion
Thanks for reading this article ❤️
I hope this blog will help you to learn about how to Implement GraphQL with HTTP in Flutter and you will be able to implement it.
For more updates, make sure to keep following Mobikul Blogs to learn more about mobile app development.
Happy Learning ✍️
Other blogs you may like…
Implementation of GraphQL API on flutter
Cache handling in GraphQL API calling in Flutter