A P I (Application Programming Interface)
APIs (Application Programming Interface) act as an interface between two
applications to interact and provide the relevant data. It uses a set of protocols
using which the operation is done before diving into the implementation, it’s
essential to understand what APIs are and how they work. An API serves as a
bridge that allows different software applications to communicate with each
other. In the context of mobile app development, APIs are often used to fetch
data from a server or a database. HTTP requests, specifically GET requests, are
commonly employed to retrieve data from APIs. When a Flutter app sends a GET
request to an API endpoint, it receives a response containing the requested
data, typically in JSON format.
API Protocols
1. REST APIs(Representational State Transfer)
o Concept: Sending a letter to a friend and getting a reply.
o Real World Example: Twitter API, where you can send a request to
get recent tweets.
2. SOAP APIs
o Concept: Sending a formal, structured letter with a specific
format.
o Real World Example: A banking API used to securely transfer
money between accounts.
3. GraphQL APIs
o Concept: Asking a librarian for specific book details and getting
just the information you need.
o Real World Example: GitHub's API where you can query for
specific data like user profiles and repositories in a single
request.
4. Webhook APIs
o Concept: Getting a notification when a package is delivered.
o Real World Example: Slack Webhooks, which send a message to a
Slack channel when a specific event happens, like a new user
registration on a website.
5. RPC APIs
o Concept: Calling a friend and asking them to perform a task for
you.
o Real World Example: Google Cloud Functions API, which allows
developers to execute code in response to events.
6. RESTful API:
Implementation of REST Principles: A RESTful API is an API that adheres
to the principles of REST architecture. It’s the practical implementation
of REST constraints.
Resource-Oriented URLs: In a RESTful API, each resource is represented
by a unique URL. For example, in a Flutter app, you might have a URL
like https://api.example.com/users/1 to access a specific user’s data.
HTTP Methods: The API uses HTTP methods like GET to retrieve data,
POST to create data, PUT to update data, and DELETE to remove data.
Statelessness: The server treats each request as independent, meaning
it doesn't keep track of any client context between requests.
Response Formats: RESTful APIs typically return data in formats like
JSON or XML. JSON is widely used in Flutter because it’s lightweight and
easy to parse.
Hypermedia as the Engine of Application State (HATEOAS): Ideally, a
RESTful API includes links in responses to guide the client on possible
actions, though this is not always strictly implemented.
Using RESTful API in Flutter:
In a Flutter app, when you consume a RESTful API, you typically use the
http package or libraries like Dio to make HTTP requests to these APIs.
You’ll send requests to the server, handle responses, and parse the JSON
data.
Example Workflow in Flutter:
1. Make a Request: Use http.get() to retrieve data from a RESTful API.
2. Parse Response: Convert the JSON response into Dart objects.
3. Update UI: Reflect the data in your app’s UI, maybe by using
FutureBuilder or StreamBuilder.
API Request Methods
1. GET
o Concept: Reading a book in a library.
o Real World Example: Requesting user information from a social
media API.
2. POST
o Concept: Submitting an application form.
o Real World Example: Creating a new post on a blog through an
API.
3. PUT
o Concept: Replacing an old poster with a new one on a bulletin
board.
o Real World Example: Updating a user's profile information on an
API.
4. DELETE
o Concept: Removing a book from a library.
o Real World Example: Deleting a user's account through an API.
5. PATCH
o Concept: Fixing a typo in a book.
o Real World Example: Updating a single field in a user's profile via
an API.
6. OPTIONS
o Concept: Asking what services a library offers.
o Real World Example: Checking which HTTP methods are supported
by a web server endpoint.
7. HEAD
o Concept: Looking at the table of contents without reading the
entire book.
o Real World Example: Checking the headers of a web page to see
metadata without downloading the whole page.
8. CONNECT
o Concept: Opening a tunnel to a friend’s house to send secret
messages.
o Real World Example: Using HTTPS to securely connect to a web
server.
9. TRACE
o Concept: Tracking the path of a letter you sent to a friend.
o Real World Example: Debugging a network connection to see the
path taken by a request.
NOTE –
While REST is a set of constraints, RESTful is an API adhering to those
constraints.
REST is the concept or architectural style.
RESTful API is the practical implementation of this concept, following REST
principles in designing APIs.
async
The Future class, part of dart: async, is used for getting the result of a
computation after an asynchronous task has completed. This Future value is
then used to do something after the computation finishes. Once the read
operation is completed, the execution control is transferred within "then()".
async*
Async and Await keywords are used to provide a declarative way to define
the asynchronous function and use their results. The async keyword is used
when we want to declare a function as asynchronous and the await keyword
is used only on asynchronous functions
sync*
In Dart language the synchronous data sequence means the instance of
Iterable . The asynchronous data sequence means the instance of Stream .
P.S. Generator functions can generate data items indefinitely until the
function returns.
sync: Tasks are done one after another. Each task waits for the previous one
to finish.
async: Tasks can be started without waiting for others to finish. You handle
the result of each task when it's done.
async*: Generates a sequence of values asynchronously, where each value
can be awaited individually as it becomes available.
API PROTOCOLS.
REST APIs
Concept:
Sending a letter to a friend and getting a reply.
Real World Example:
Twitter API, where you can send a request to get recent tweets.
Syntax Example:
dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchTweets() async {
final response = await http.get(Uri.parse('https://api.twitter.com/2/tweets'), headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
});
if (response.statusCode == 200) {
var tweets = json.decode(response.body);
print(tweets);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
fetchTweets();
}
SOAP APIs
Concept:
Sending a formal, structured letter with a specific format.
Real World Example:
A banking API used to securely transfer money between accounts.
Syntax Example:
dart
Copy code
import 'package:http/http.dart' as http;
Future<void> transferMoney() async {
final soapRequest = '''
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ser="http://service.bank.com/">
<soapenv:Header/>
<soapenv:Body>
<ser:transferMoney>
<amount>100</amount>
<fromAccount>123456</fromAccount>
<toAccount>654321</toAccount>
</ser:transferMoney>
</soapenv:Body>
</soapenv:Envelope>''';
final response = await http.post(
Uri.parse('https://api.bank.com/transfer'),
headers: {'Content-Type': 'text/xml'},
body: soapRequest
);
if (response.statusCode == 200) {
print(response.body);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
transferMoney();
}
GraphQL APIs
Concept:
Asking a librarian for specific book details and getting just the information you need.
Real World Example:
GitHub's API where you can query for specific data like user profiles and repositories in
a single request.
Syntax Example:
dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchGitHubData() async {
final query = '''
{
user(login: "octocat") {
name
repositories(first: 5) {
nodes {
name
}
}
}
}''';
final response = await http.post(
Uri.parse('https://api.github.com/graphql'),
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
},
body: json.encode({'query': query})
);
if (response.statusCode == 200) {
var data = json.decode(response.body);
print(data);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
fetchGitHubData();
}
Webhook APIs
Concept:
Getting a notification when a package is delivered.
Real World Example:
Slack Webhooks, which send a message to a Slack channel when a specific event
happens, like a new user registration on a website.
Syntax Example:
dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> sendSlackNotification() async {
final webhookUrl =
'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXX
XX';
final message = json.encode({'text': 'New user has registered!'});
final response = await http.post(
Uri.parse(webhookUrl),
headers: {'Content-Type': 'application/json'},
body: message
);
if (response.statusCode == 200) {
print('Message sent successfully');
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
sendSlackNotification();
}
RPC APIs
Concept:
Calling a friend and asking them to perform a task for you.
Real World Example:
Google Cloud Functions API, which allows developers to execute code in response to
events.
Syntax Example:
dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> callFunction() async {
final url = 'https://cloudfunctions.googleapis.com/v1/projects/YOUR_PROJECT_ID/
locations/us-central1/functions/functionName:call';
final headers = {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
};
final data = json.encode({'param': 'value'});
final response = await http.post(Uri.parse(url), headers: headers, body: data);
if (response.statusCode == 200) {
var result = json.decode(response.body);
print(result);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
callFunction();
}
API Request Methods
GET
Concept:
Reading a book in a library.
Real World Example:
Requesting user information from a social media API.
Syntax Example:
dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchUserData() async {
final response = await http.get(Uri.parse('https://api.example.com/users/12345'));
if (response.statusCode == 200) {
var userData = json.decode(response.body);
print(userData);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
fetchUserData();
}
POST
Concept:
Submitting an application form.
Real World Example:
Creating a new post on a blog through an API.
Syntax Example:
dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> createPost() async {
final data = json.encode({
'title': 'New Blog Post',
'content': 'This is the content of the new blog post.'
});
final response = await http.post(
Uri.parse('https://api.example.com/posts'),
headers: {'Content-Type': 'application/json'},
body: data
);
if (response.statusCode == 201) {
var newPost = json.decode(response.body);
print(newPost);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
createPost();
}
PUT
Concept:
Replacing an old poster with a new one on a bulletin board.
Real World Example:
Updating a user's profile information on an API.
Syntax Example:
dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> updateUser() async {
final data = json.encode({
'name': 'New Name',
'email': 'newemail@example.com'
});
final response = await http.put(
Uri.parse('https://api.example.com/users/12345'),
headers: {'Content-Type': 'application/json'},
body: data
);
if (response.statusCode == 200) {
var updatedUser = json.decode(response.body);
print(updatedUser);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
updateUser();
}
DELETE
Concept:
Removing a book from a library.
Real World Example:
Deleting a user's account through an API.
Syntax Example:
dart
Copy code
import 'package:http/http.dart' as http;
Future<void> deleteUser() async {
final response = await http.delete(Uri.parse('https://api.example.com/users/12345'));
if (response.statusCode == 204) {
print('User deleted successfully');
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
deleteUser();
}
PATCH
Concept:
Fixing a typo in a book.
Real World Example:
Updating a single field in a user's profile via an API.
Syntax Example:
dart
Copy code
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> patchUser() async {
final data = json.encode({'email': 'newemail@example.com'});
final response = await http.patch(
Uri.parse('https://api.example.com/users/12345'),
headers: {'Content-Type': 'application/json'},
body: data
);
if (response.statusCode == 200) {
var updatedUser = json.decode(response.body);
print(updatedUser);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
patchUser();
}
OPTIONS
Concept:
Asking what services a library offers.
Real World Example:
Checking which HTTP methods are supported by a web server endpoint.
Syntax Example:
dart
Copy code
import 'package:http/http.dart' as http;
Future<void> checkOptions() async {
final response = await http.options(Uri.parse('https://api.example.com/users'));
if (response.statusCode == 200) {
print(response.headers);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
checkOptions();
}
HEAD
Concept:
Looking at the table of contents without reading the entire book.
Real World Example:
Checking the headers of a web page to see metadata without downloading the whole
page.
Syntax Example:
dart
Copy code
import 'package:http/http.dart' as http;
Future<void> checkHeaders() async {
final response = await http.head(Uri.parse('https://api.example.com/users/12345'));
if (response.statusCode == 200) {
print(response.headers);
} else {
print('Error: ${response.statusCode}');
}
}
void main() {
checkHeaders();
}
CONNECT
Concept:
Opening a tunnel to a friend’s house to send secret messages.
Real World Example:
Using HTTPS to securely connect to a web server.
(Note: Dart's http library does not support CONNECT method directly. This is more
commonly handled by lower-level libraries or tools like curl.)
TRACE
Concept:
Tracking the path of a letter you sent to a friend.
Real World Example:
Debugging a network connection to see the path taken by a request.
(Note: TRACE requests are not commonly used in practice and might be blocked for
security reasons.)
curl -X TRACE https://api.example.com
This provides a detailed explanation and Dart syntax examples for each API concept,
making it easier to understand and implement them in real-world scenarios.
What is an HTTP response code
HTTP response code is the language of web servers that translates browser requests
into understandable instructions. It is like a poet answering virtual questions, giving
them meaning and direction. Response codes are not always HTTP error codes. For
example, “200 OK” means everything is OK, but HTTP Error “404 Not Found” means
when the page is lost in the virtual space. Each code is a unique expression of the
server state, the decoding of which allows us to understand what is happening on the
other side of the virtual world.
1xx codes (Information)
1xx status codes in the HTTP protocol are a kind of first link in the dialogue between
the server and the client. Instead of providing a complete response to a request, they
provide information about the current status, making data exchange more efficient.
Let's take a closer look at them:
100 Continue. HTTP response code in which the server gives the green light to the
user, allowing him to safely continue sending a large request.
101 Switching Protocols. The server tells the client that it is changing the rules of
the game, for example, moving from HTTP to the more secure HTTPS. In this case, the
“Upgrade” header is used for the protocol change.
102 Processing. This code is like a message that the server has accepted the request,
but is still busy with a complex operation.
103 Early Hints. Here the server sends several indicative headers to the client before
the main response, warning about something that may be relevant in the near future.
2xx code (Successful)
HTTP error codes in the group 2xx indicate a successful request from the server. They
essentially act as a “green light” in the scope of web communications, confirming that
everything is going according to plan and has been successfully completed.
200 OK. This status is used when the server processes a request by GET method
without problems and returns the requested data in response. The "Content-Type"
header reports the content type in the response. It just informs the client that the
request was successful.
201 Created. Here the server announces the creation of a new resource.
202 Accepted. The server lets the user know that the request has been accepted, but
will take time to respond.
203 Non—Authoritative Information. This code provides the client with data that
may not be official, but can be used for comparison.
204 No Content. The server has processed the request but is not returning any
additional content.
205 Reset Content. Here the client is instructed to reset the current view or data
after sending.
206 Partial Content. This case indicates that the response contains only part of the
requested content. The "Content-Range" header indicates the partial content range.
207 Multi-Status. The server has successfully completed a multi-operation request
from the client, and the response contains information about the status of each of the
operations.
226 IM Used. This code indicates that the server used the Incremental Metadata (IM)
method and responded by passing only the modified resource parts to the client.
3xx codes (Redirects)
3xx codes in the HTTP protocol are like pointers that guide the user to a new resource
location. They inform the client that follow-up steps must be taken to obtain the
requested content or to be redirected to another resource. Let's immerse into the
details of each of them:
300 Multiple Choices. The client receives a signal that there are several possible
locations for the resource and is given a choice in response. In current circumstances,
the "Location" header may indicate alternative options for the resource.
301 Moved Permanently. The server reports back to the user that the resource has
been permanently moved to another location.
302 Found. This HTTP code is similar to a temporary redirect. The server informs the
consumer that the resource is temporarily available at a different URL. The "Location"
header points to the new URL for the temporary redirect.
303 See Other. The client is told that the resource is available at a different URL and
must make a GET request to this new address.
304 Not Modified. This status tells the client that the resource has remained
unchanged since the last request and does not need to be downloaded again. When
making a request, the "If-Modified-Since" header is used to check if the resource has
been modified.
305 Use Proxy. As a response, the server reports that it should use the specified
proxy to access the requested resource.
306 (reserved) — The code has been reserved, but in fact it is not used.
307 Temporary Redirect. This code is similar to 302 Found, but requires the client to
remain in the request method that was used in the original request.
308 Permanent Redirect. Indicates that the resource has made a permanent move
to a new URI and the client should use the new URI for all future requests.
4xx HTTP Error (Client errors)
HTTP 4xx error codes indicate client errors. This means that the problem is on the user
side, such as the web browser or app.
400 Bad Request. The server cannot process the request due to syntax errors, invalid
data, or other errors on the client side.
401 Unauthorized. The server cannot process the request due to syntax errors,
invalid data, or other errors on the client side.
402 Payment Required. The code is not active at the moment and is reserved for
future use. It may indicate the need to pay before accessing the resource in the future.
HTTP Error 403 Forbidden. The client does not have sufficient rights to access the
requested resource.
404 Not Found. The requested resource does not exist on the server. This is one of
the most common user errors.
405 Method Not Allowed. The server does not support the specified request method
in during this resource. The “Allow” header indicates the allowed methods for the
resource. With this code,
406 Not Acceptable. The server cannot provide data in a format that can be
accepted by the client.
407 Proxy Authentication Required. Authentication on proxy server is required for
access the requested resource.
408 Request Timeout. The server was waiting to receive a request from the client,
but timed out. The "Retry-After" header may indicate the time after which the request
can be retried.
409 Conflict. The request cannot be completed due to a conflict with the current
resource state.
410 Gone. The requested resource previously existed but has now been deleted and
its restoration is not expected.
411 Length Required. The server demands to specify the content length in the
request; the absence of this information is considered an error.
412 Precondition Failed. A precondition in the request is not met, that prevents it
from executing.
413 Payload Too Large. The size of the request data exceeds the server limits.
414 URI Too Long. URI length in the request exceeds acceptable limits.
415 Unsupported Media Type. The server cannot process the data type provided in
the request.
416 Range Not Satisfiable. HTTP error where the requested range does not match
the current server data.
417 Expectation Failed. The expected condition in the "Expect" header was not met.
418 I’m a teapot. This code is included as a joke and does not imply any real action
for the user or server, and is not a full-fledged error. It indicates that the server is a
teapot and is not capable of making coffee.
421 Misdirected Request. The server does not process the request due to an error in
the request or server configuration.
422 Unprocessable Entity. The server understands the request, but does not process
it due to data errors.
423 Locked. The resource is blocked and cannot be processed.
424 Failed Dependency. The request depends on another unexecuted request.
425 Too Early. The server is not ready to process the request due to its early coming.
426 Upgrade Required. The server requires the use of a more advanced protocol to
process the request.
428 Precondition Required. The server requires certain preconditions to be specified
in the request.
429 Too Many Requests. The client sent too many requests in a short time,
exceeding the server's limits.
431 Request Header Fields Too Large. Request headers exceed the maximum
allowed size.
449 Retry with. Indicates that the request cannot be run by the current server, but
can be successfully processed by another server, and the client should retry the
request with a new URI.
451 Unavailable for Legal Reasons. The resuource is unavailable for legal reasons.
499 Client Closed Request. The server received the request, but the connection was
closed by the client before processing completion.
HTTP 5xx error (Server errors)
HTTP 5xx error codes indicate the server problems. These codes indicate problems that
have occurred on the server side, making the server unable to process the user's
request in a right way. Let's take a closer look at them:
HTTP Error 500 Internal Server Error. The server encounters unexpected
circumstances that prevent it from the request completion The "Server" header may
indicate the server on which the error occurred.
501 Not Implemented. The server does not support the functionality required to
process the client's request. The "Via" header may indicate the proxy server through
which the error occurred.
502 Bad Gateway. This code means that the server that acts as proxy received an
incorrect response from another server.
HTTP Error 503 Service Unavailable. The server is temporarily unable to process
requests.
504 Gateway Timeout. The server, that acts as proxy, did not receive a timely
response from another server.
505 HTTP Version Not Supported. The server does not support the HTTP protocol
version specified in the request. As a backup option, the "Upgrade" header may
indicate supported protocols.
506 Variant Also Negotiates. This status is not used in HTTP/1.1; however, if the
server detects an internal configuration that results in content negotiation ambiguity, it
may use this response.
507 Insufficient Storage. The server cannot fulfill the request due to insufficient
storage space on the server.
508 Loop Detected. The server has detected a loop while processing the request, and
refuses to complete the request in order to avoid an infinite loop.
509 Bandwidth Limit Exceeded. The error occurs when the server's bandwidth is
exceeded due to high volume of requests or traffic.
510 Not Extended. The client must transfer additional extensions to continue the
request.
511 Network Authentication Required. The client must authenticate itself in order
to gain access to the network.
How to check the page status code
In this section, we'll give consideration to three main ways to check the page status
code: via the command line, using a web browser, and using independent online
services. Each of these methods has its own advantages and can be useful in different
situations.
Checking server response via command line
The command line provides a convenient way to check the page status code without
having to use a web browser. For this method, you need to open the command line and
use the command:
Copy
curl -I http://page-address
This command sends a HEAD request (headers only request) to the specified URL and
displays information including the HTTP status code:
The example above shows a successful response code. In the case of a response that
contains an error code, such as 404 Not Found HTTP error, the result will look similar:
Checking the server response via the browser console
The web browser developer console provides tools for conducting various operations,
including checking the page status code. In order to see the HTTP code in the server
response, you need to open the developer console (Ctrl+Shift+K) or (Ctrl+shift+J)
depending on the browser used. Next, select the “network” section and load the
desired page:
Checking the server response using independent tools
There are a large number of independent online services that provide tools to check the
website page status code. These services usually allow you to quickly receive an
overview of your resource's availability and performance. They all operate using the
same principle. As an example, we will consider the most popular resource
- httpstatus.io
First of all, you need to open the service itself, then enter the address of the page
which answer you need to find out, and request verification:
Rest api url
Rest api endpoint
url followed by endpoint
import package
create a constant file that stores url and endpoint
create a model clas
Create a file that handles the API call, and write specific methods to fetch
and parse data
Use data in app