Popular Searches
Popular Course Categories
Popular Courses

Handling GET, POST, PUT, PATCH, and DELETE Requests

Handling GET, POST, PUT, PATCH, and DELETE Requests

API Integration and Network Requests

Handling GET, POST, PUT, PATCH, and DELETE Requests in React Native

Course: React Native Training

Topic: Handling GET, POST, PUT, PATCH, and DELETE Requests

Course Link: React Native Training at JustAcademy

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to HTTP Requests in React Native

Modern mobile applications communicate with backend servers to retrieve information, submit forms, update records, and delete resources. For example, a shopping application retrieves products, creates orders, updates delivery details, and removes items from a cart.

React Native provides the Fetch API for making network requests. Fetch allows developers to communicate with REST APIs using HTTP methods such as GET, POST, PUT, PATCH, and DELETE.

Each HTTP method communicates the purpose of a request. Choosing the correct method helps an application interact with backend services consistently and predictably.

Official reference: React Native Networking Documentation.

1.1 What Is an HTTP Request?

An HTTP request is a message sent by a client to a server to retrieve or manipulate a resource. In a React Native application, the client is the mobile app, and the server usually exposes an API endpoint.

An HTTP request may include the following elements:

  • URL: The address of the API endpoint.
  • Method: The intended operation, such as GET or POST.
  • Headers: Additional information about the request, such as the content type or authentication token.
  • Body: Data sent to the server, commonly with POST, PUT, or PATCH.

1.2 What Is the Fetch API?

The Fetch API is a JavaScript interface for making network requests. It returns a Promise that resolves to a Response object when a response is received.

fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Request failed:', error);
  });

In this example, Fetch sends a request to the endpoint, the response body is parsed as JSON, and the returned data is printed in the console.

2. Understanding the Five Main HTTP Methods

GET, POST, PUT, PATCH, and DELETE are commonly used when working with REST APIs. Their exact behavior depends on the API's implementation and documentation.

Method Primary Purpose Typical Example Request Body
GET Retrieve data. Fetch a list of products. Normally not used.
POST Submit data or create a resource. Create a new user. Commonly used.
PUT Replace a resource. Replace a complete user record. Commonly used.
PATCH Partially update a resource. Change only a user's email. Commonly used.
DELETE Request deletion of a resource. Delete a product. Optional and API-dependent.

2.1 Typical CRUD Operations

CRUD stands for Create, Read, Update, and Delete. These operations are the foundation of many applications that store and manage data.

  • Create: Commonly performed using POST.
  • Read: Commonly performed using GET.
  • Update: Commonly performed using PUT or PATCH.
  • Delete: Commonly performed using DELETE.

PUT commonly replaces a resource, while PATCH commonly changes selected fields. The server's API contract determines the exact behavior of each operation.

3. Setting Up a Testing API

Before writing network code, choose an API endpoint that supports the operations required by the application. For practice, JSONPlaceholder provides sample resources such as posts and users.

Testing API: JSONPlaceholder

Example endpoints:

  • Get all posts: https://jsonplaceholder.typicode.com/posts
  • Get one post: https://jsonplaceholder.typicode.com/posts/1
  • Create a post: https://jsonplaceholder.typicode.com/posts
  • Update a post: https://jsonplaceholder.typicode.com/posts/1
  • Delete a post: https://jsonplaceholder.typicode.com/posts/1

JSONPlaceholder is intended for testing and demonstration. Write operations may return simulated results without permanently changing stored data.

3.1 Common Fetch Options

fetch(url, {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Sample Title'
  })
});
  • url identifies the endpoint.
  • method specifies the HTTP method.
  • headers contains request metadata.
  • body contains the data being sent, when required.

4. Handling GET Requests

A GET request retrieves information from a server. It is useful for loading product lists, user profiles, articles, categories, and other resources.

4.1 Basic GET Request

const getPosts = async () => {
  try {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/posts'
    );

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const posts = await response.json();
    console.log(posts);
  } catch (error) {
    console.error('Unable to retrieve posts:', error.message);
  }
};

getPosts();

4.2 Explanation of the GET Request

  1. The function is declared with async so it can use await.
  2. Fetch sends a GET request to the posts endpoint by default.
  3. The application checks response.ok to determine whether the HTTP status indicates success.
  4. response.json() reads and parses the response body.
  5. The parsed posts are available for further processing or display.
  6. The catch block handles rejected requests and errors thrown in the try block.

4.3 GET Request for a Single Resource

const getPostById = async (postId) => {
  try {
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/posts/${postId}`
    );

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const post = await response.json();
    return post;
  } catch (error) {
    console.error('Unable to retrieve post:', error.message);
    throw error;
  }
};

getPostById(1)
  .then(post => console.log(post.title))
  .catch(error => console.error(error.message));

4.4 When Should You Use GET?

  • Retrieving all products from an API.
  • Loading user information.
  • Displaying articles or blog posts.
  • Retrieving order history.
  • Searching or filtering data through query parameters supported by an endpoint.
  • Loading information when a screen opens.

5. Handling POST Requests

A POST request submits information to a server. It is commonly used to create a resource, submit a registration form, create a new post, or send a contact message.

5.1 Basic POST Request

const createPost = async () => {
  const postData = {
    title: 'Learning React Native',
    body: 'Practicing POST requests.',
    userId: 1
  };

  try {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/posts',
      {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(postData)
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const createdPost = await response.json();
    console.log('Created post:', createdPost);
  } catch (error) {
    console.error('Unable to create post:', error.message);
  }
};

createPost();

5.2 Explanation of the POST Request

  • method: 'POST' specifies the HTTP method.
  • headers declares the expected response and the request body format.
  • Content-Type: application/json tells the server that the body contains JSON.
  • postData is the object being submitted.
  • JSON.stringify(postData) converts the JavaScript object to a JSON string.
  • response.json() parses the server's JSON response.

5.3 POST Requests with Form Data

Mobile applications frequently submit registration, contact, feedback, or profile forms. The form values can be validated and sent as a JSON object if that is what the backend expects.

const submitContactForm = async (name, email, message) => {
  if (!name.trim() || !email.trim()) {
    throw new Error('Name and email are required.');
  }

  const response = await fetch(
    'https://api.example.com/contact',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json'
      },
      body: JSON.stringify({
        name: name.trim(),
        email: email.trim(),
        message: message.trim()
      })
    }
  );

  if (!response.ok) {
    throw new Error(`Submission failed: ${response.status}`);
  }

  return response.json();
};

The endpoint above is illustrative. Replace it with the actual contact API and follow the server's required payload and response format.

5.4 Common Uses of POST

  • User registration.
  • Login requests.
  • Creating posts, products, or orders.
  • Submitting feedback or contact forms.
  • Sending data to a server for processing.

6. Handling PUT Requests

A PUT request is commonly used to replace the representation of an existing resource. The client usually identifies the resource through the endpoint URL and sends the updated representation in the request body.

6.1 Basic PUT Request

const replacePost = async () => {
  const updatedPost = {
    id: 1,
    title: 'Updated React Native Guide',
    body: 'This is the replacement post content.',
    userId: 1
  };

  try {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/posts/1',
      {
        method: 'PUT',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(updatedPost)
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const result = await response.json();
    console.log('Updated post:', result);
  } catch (error) {
    console.error('Unable to replace post:', error.message);
  }
};

replacePost();

6.2 How PUT Works

  1. Identify the resource that needs updating.
  2. Prepare the complete representation required by the API.
  3. Set the request method to PUT.
  4. Serialize the request object using JSON.stringify().
  5. Send the request to the resource endpoint.
  6. Check the HTTP status and process the response as documented by the API.

6.3 When Should You Use PUT?

  • Replacing an existing profile record.
  • Updating a complete product representation.
  • Submitting all editable fields for an existing resource.

Do not assume that every backend treats PUT identically. Check whether the endpoint expects all fields, how omitted fields are handled, and whether the operation creates a resource when one does not already exist.

7. Handling PATCH Requests

A PATCH request is used to apply a partial modification to a resource. It is useful when only one or a few fields need to be changed.

7.1 Basic PATCH Request

const updatePostTitle = async () => {
  const changes = {
    title: 'Updated Post Title'
  };

  try {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/posts/1',
      {
        method: 'PATCH',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(changes)
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const updatedPost = await response.json();
    console.log('Updated post:', updatedPost);
  } catch (error) {
    console.error('Unable to update post:', error.message);
  }
};

updatePostTitle();

7.2 How PATCH Works

  1. Identify the resource to update.
  2. Prepare an object containing only the fields that should change.
  3. Set the request method to PATCH.
  4. Serialize the update object.
  5. Send the request to the resource endpoint.
  6. Check the response status and update the UI when successful.

7.3 PUT vs PATCH

PUT PATCH
Commonly replaces a resource representation. Commonly applies partial changes.
Often sends the complete set of fields expected by the API. Often sends only the fields that need updating.
Useful for replacing a profile or record. Useful for changing a name, status, or selected setting.
Idempotent according to HTTP semantics. Idempotency depends on the particular patch operation and API behavior.

8. Handling DELETE Requests

A DELETE request asks the server to remove a specified resource. It is commonly used for deleting posts, removing products, cancelling records, or deleting a user's saved item.

8.1 Basic DELETE Request

const deletePost = async (postId) => {
  try {
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/posts/${postId}`,
      {
        method: 'DELETE'
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    console.log('Delete request completed.');
  } catch (error) {
    console.error('Unable to delete post:', error.message);
  }
};

deletePost(1);

8.2 Important Points About DELETE

  • The endpoint commonly includes the ID of the resource to delete.
  • The request body is often unnecessary, but some APIs define a body for particular DELETE operations.
  • A successful response may include a body or return HTTP 204 No Content.
  • Do not automatically parse JSON if the server returns an empty body.
  • Update the local UI after the server confirms the operation according to the API's response contract.
  • Use a confirmation prompt before deleting important user data.

8.3 Removing a Deleted Item from Local State

const removePostFromList = (postId) => {
  setPosts(currentPosts =>
    currentPosts.filter(post => post.id !== postId)
  );
};

This function updates the local list by removing the matching record. Call it after the delete operation has succeeded, unless the application deliberately uses an optimistic update strategy with rollback handling.

9. Understanding HTTP Status Codes

HTTP status codes tell the client how the server handled a request. Applications should interpret status codes rather than assuming every resolved Fetch request represents success.

Status Code Meaning Typical Use
200 OK The request succeeded. Retrieving or updating a resource.
201 Created A resource was created. Successful POST request.
202 Accepted The request was accepted for processing. Asynchronous server operation.
204 No Content The request succeeded without a response body. Some DELETE or update operations.
400 Bad Request The request was invalid. Missing or incorrectly formatted fields.
401 Unauthorized Authentication is missing or invalid. Expired or absent credentials.
403 Forbidden The caller is not permitted to perform the operation. Insufficient permissions.
404 Not Found The endpoint or resource was not found. Invalid resource ID.
409 Conflict The request conflicts with the current resource state. Duplicate or conflicting update.
422 Unprocessable Content The request format is understood but the data cannot be processed. Validation failure on APIs using this status.
429 Too Many Requests The rate limit was exceeded. Too many requests in a time window.
500 Internal Server Error The server encountered an error. Unexpected backend failure.

9.1 Why response.ok Matters

Fetch generally rejects its Promise for network-level failures, but it does not automatically reject for HTTP error responses such as 404 or 500. The application should inspect response.ok or response.status.

const response = await fetch(url);

if (!response.ok) {
  throw new Error(`HTTP error: ${response.status}`);
}

const data = await response.json();

10. Understanding Request Headers and JSON Bodies

Headers provide metadata about a request. For JSON-based REST APIs, two commonly used headers are Accept and Content-Type.

10.1 Accept Header

The Accept header indicates the response media types that the client can process.

headers: {
  Accept: 'application/json'
}

10.2 Content-Type Header

The Content-Type header identifies the format of the request body.

headers: {
  'Content-Type': 'application/json'
}

10.3 JSON.stringify()

JavaScript objects must generally be serialized before they can be sent as JSON request bodies.

const user = {
  name: 'Priya',
  email: '[email protected]'
};

const requestBody = JSON.stringify(user);

The resulting string can be passed to the Fetch request's body option. The backend must support the submitted content type and expected fields.

11. Creating a Reusable API Request Function

When an application contains many endpoints, repeated request logic can become difficult to maintain. A reusable API function can centralize the base URL, headers, status checking, and response parsing.

11.1 Reusable JSON Request Helper

const API_BASE_URL = 'https://jsonplaceholder.typicode.com';

export async function requestJson(path, options = {}) {
  const response = await fetch(`${API_BASE_URL}${path}`, {
    ...options,
    headers: {
      Accept: 'application/json',
      ...(options.headers || {})
    }
  });

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  if (response.status === 204) {
    return null;
  }

  return response.json();
}

11.2 Using the Helper for GET

const posts = await requestJson('/posts');

11.3 Using the Helper for POST

const newPost = await requestJson('/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Fetch API',
    body: 'Learning HTTP methods',
    userId: 1
  })
});

11.4 Using the Helper for PUT

const replacedPost = await requestJson('/posts/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    id: 1,
    title: 'Updated Title',
    body: 'Updated Body',
    userId: 1
  })
});

11.5 Using the Helper for PATCH

const patchedPost = await requestJson('/posts/1', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Partially Updated Title'
  })
});

11.6 Using the Helper for DELETE

await requestJson('/posts/1', {
  method: 'DELETE'
});

This helper assumes successful non-empty responses contain JSON. For a production API, adjust it to handle text responses, empty responses, error bodies, and other content types according to the API contract.

12. Integrating HTTP Methods with React Native UI

API requests are usually triggered by screen loading or user actions. GET requests can load data when a screen opens, while POST, PUT, PATCH, and DELETE requests are often initiated by buttons or form submissions.

12.1 Example: Load and Display Posts

import React, { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Button,
  FlatList,
  Text,
  View
} from 'react-native';

export default function PostsScreen() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const loadPosts = async () => {
    setLoading(true);
    setError('');

    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/posts'
      );

      if (!response.ok) {
        throw new Error(`HTTP error: ${response.status}`);
      }

      const data = await response.json();
      setPosts(data);
    } catch (err) {
      setError(err.message || 'Unable to load posts.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadPosts();
  }, []);

  if (loading) {
    return <ActivityIndicator size="large" />;
  }

  if (error) {
    return (
      <View>
        <Text>{error}</Text>
        <Button title="Retry" onPress={loadPosts} />
      </View>
    );
  }

  if (posts.length === 0) {
    return <Text>No posts available.</Text>;
  }

  return (
    <FlatList
      data={posts}
      keyExtractor={item => String(item.id)}
      renderItem={({ item }) => (
        <View>
          <Text>{item.title}</Text>
          <Text>{item.body}</Text>
        </View>
      )}
      onRefresh={loadPosts}
      refreshing={loading}
    />
  );
}

12.2 Explanation

  • useState stores the posts, loading flag, and error message.
  • loadPosts makes the GET request.
  • useEffect starts loading when the component mounts.
  • FlatList renders the list efficiently.
  • The Retry button allows the user to repeat a failed request.
  • The refresh properties support pull-to-refresh behavior on the list.

13. Updating the UI After POST, PUT, PATCH, and DELETE

After a write request succeeds, the application needs to decide how to update its visible data. It can fetch the updated resource again, update local state from the response, or optimistically update the interface and restore the previous state if the request fails.

13.1 Update Local State After POST

setPosts(currentPosts => [createdPost, ...currentPosts]);

13.2 Update Local State After PUT or PATCH

setPosts(currentPosts =>
  currentPosts.map(post =>
    post.id === updatedPost.id ? updatedPost : post
  )
);

13.3 Update Local State After DELETE

setPosts(currentPosts =>
  currentPosts.filter(post => post.id !== deletedPostId)
);

Use the actual response returned by the backend where possible. Some APIs return only a status code or an empty body, so the application may need to update the local state using known request information or refetch the resource.

14. Managing Loading and Error States for Write Requests

Creating or modifying data should provide clear feedback to the user. A form should indicate when it is submitting, prevent accidental duplicate submissions where appropriate, and display an error if the server rejects the request.

14.1 Example of a Submission State

const [submitting, setSubmitting] = useState(false);
const [message, setMessage] = useState('');

const submitPost = async (postData) => {
  if (submitting) return;

  setSubmitting(true);
  setMessage('');

  try {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/posts',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(postData)
      }
    );

    if (!response.ok) {
      throw new Error(`Submission failed: ${response.status}`);
    }

    const result = await response.json();
    setMessage('Post submitted successfully.');
    return result;
  } catch (error) {
    setMessage('Unable to submit the post. Please try again.');
    throw error;
  } finally {
    setSubmitting(false);
  }
};

When calling this function from a UI event handler, handle the re-thrown error to avoid an unhandled Promise rejection. The example also assumes the server returns JSON on success.

15. Handling Network Errors and Failed Requests

Requests can fail because of an unavailable network, an incorrect endpoint, expired credentials, server errors, or invalid data. A good application handles these conditions without crashing.

15.1 Common Error Types

Error Possible Cause Recommended Action
Network failure Connection unavailable or server unreachable. Check connectivity and endpoint configuration.
400 Bad Request Invalid payload or parameters. Validate the submitted data.
401 Unauthorized Missing or invalid authentication. Follow the API's authentication flow.
403 Forbidden Insufficient permission. Check the user's access rights.
404 Not Found Resource or endpoint does not exist. Verify the URL and resource ID.
409 Conflict Request conflicts with current server state. Resolve the conflict according to API rules.
422 Unprocessable Content Submitted fields fail server validation. Display relevant validation feedback.
429 Too Many Requests Rate limit exceeded. Respect rate limits and retry guidance.
500-level status Server-side failure. Show a friendly message and retry when appropriate.
JSON parsing failure Response body is empty or malformed. Check the expected response format.

15.2 Important Error-Handling Rules

  • Check response.ok after each request.
  • Do not assume every successful HTTP response contains JSON.
  • Do not show raw technical error details to end users.
  • Log only safe diagnostic information.
  • Offer retry functionality when repeating the operation is safe.
  • Be careful when automatically retrying POST requests because they may create duplicate records.

16. Request Cancellation and Outdated Requests

Sometimes a user leaves a screen before a request finishes. Search screens can also generate multiple requests while the user types. Cancellation and stale-response protection can help prevent unnecessary work and outdated data from being displayed.

16.1 Using AbortController

const controller = new AbortController();

try {
  const response = await fetch(
    'https://jsonplaceholder.typicode.com/posts',
    {
      signal: controller.signal
    }
  );

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  const posts = await response.json();
  console.log(posts);
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Request was cancelled.');
  } else {
    console.error('Request failed:', error.message);
  }
}

// Cancel the request when it is no longer needed:
controller.abort();

In a component, the controller is typically created inside the relevant effect, and the effect cleanup function calls abort(). Verify cancellation behavior in the React Native versions and platforms supported by your application.

16.2 When to Use Cancellation

  • When a component is no longer interested in a pending request.
  • When a search term changes and an older request is obsolete.
  • When the user switches between data sources or filters.
  • When a long-running read request should be stopped.

Cancellation stops the client from continuing to wait for a supported request. It does not guarantee that the server has not already processed a write operation.

17. API Security Best Practices

Mobile applications should communicate securely with backend services. Network requests must follow the API's authentication and authorization rules.

  • Use HTTPS for production endpoints.
  • Never embed privileged server secrets in React Native source code.
  • Use the authentication mechanism documented by the backend.
  • Store persistent credentials using suitable secure storage.
  • Validate input on both the client and server.
  • Do not log passwords, access tokens, or sensitive personal information.
  • Handle expired tokens and unauthorized responses correctly.
  • Do not rely on frontend checks as a substitute for backend authorization.
  • Follow the backend's rate limits and request-size restrictions.

18. Common Mistakes and Solutions

Mistake Problem Solution
Using the wrong HTTP method The server may reject the request or perform the wrong operation. Follow the API documentation.
Forgetting JSON.stringify() The body may not contain valid JSON. Serialize JavaScript objects before sending JSON.
Missing Content-Type The backend may not recognize the payload format. Set the required content type.
Ignoring response.ok HTTP errors may be treated as success. Check the response status explicitly.
Always parsing JSON Empty responses may cause parsing errors. Follow the response contract and handle 204 responses.
Not handling loading state The user receives no feedback while the request runs. Display a loading indicator or disabled submit button.
Sending duplicate submissions Duplicate resources or operations may occur. Prevent repeated submissions and use backend idempotency support where available.
Updating the UI before confirmation The interface can show changes that failed on the server. Confirm success or implement optimistic updates with rollback.
Using HTTP in production Data may be exposed or blocked by platform security rules. Use HTTPS.
Hardcoding secrets Credentials can be extracted from the app bundle. Keep privileged secrets on the server.

19. Best Practices for GET, POST, PUT, PATCH, and DELETE

  • Use GET to retrieve data without changing server state.
  • Use POST for submissions or resource creation according to the API contract.
  • Use PUT when the API expects a resource replacement.
  • Use PATCH when the API supports partial updates.
  • Use DELETE to request resource removal.
  • Check HTTP status codes before treating requests as successful.
  • Send request bodies in the format expected by the server.
  • Use async/await with try/catch for readable asynchronous code.
  • Handle loading, success, empty, and error states.
  • Use reusable API service functions to reduce duplicated logic.
  • Validate submitted data and handle backend validation errors.
  • Protect credentials and use secure network connections.
  • Test requests with successful responses, HTTP errors, network failures, and empty response bodies.

20. Mini Project: CRUD Operations for a Posts App

Project Objective: Build a React Native application that demonstrates all five HTTP methods using a posts API.

20.1 Project Features

  • Retrieve and display posts using GET.
  • Create a new post using POST.
  • Replace an existing post using PUT.
  • Update a single field using PATCH.
  • Delete a post using DELETE.
  • Display loading and error messages.
  • Refresh the list after successful changes when necessary.
  • Prevent duplicate submissions while an operation is in progress.

20.2 API Endpoints

Operation Method Endpoint
Retrieve posts GET /posts
Retrieve one post GET /posts/1
Create post POST /posts
Replace post PUT /posts/1
Partially update post PATCH /posts/1
Delete post DELETE /posts/1

Base URL for the practice project: https://jsonplaceholder.typicode.com.

20.3 Suggested Folder Structure

src/
  components/
    PostCard.js
    LoadingView.js
    ErrorMessage.js
  screens/
    PostsScreen.js
    CreatePostScreen.js
    EditPostScreen.js
  services/
    api.js
  App.js

20.4 Implementation Steps

  1. Create a React Native project and prepare the screen structure.
  2. Create an API service module for common request logic.
  3. Implement GET to retrieve and display posts.
  4. Create a form for submitting a new post through POST.
  5. Build an edit form that replaces a post through PUT.
  6. Add a partial edit option that updates a selected field through PATCH.
  7. Add a delete button that sends a DELETE request after confirmation.
  8. Check each response status and handle errors.
  9. Update local state or refetch the list after successful operations.
  10. Test all five methods and the associated loading, success, and failure states.

20.5 Expected Learning Outcome

After completing this project, learners should understand how to send different HTTP methods from React Native, serialize JSON request bodies, inspect responses, manage asynchronous operations, and keep the interface synchronized with backend data.

21. Practical Exercises

  1. Retrieve all users from a testing API using GET.
  2. Retrieve one user by ID and display their details.
  3. Create a new post using POST.
  4. Update all fields of a sample post using PUT.
  5. Change only the title of a post using PATCH.
  6. Delete a sample post using DELETE.
  7. Create a reusable function that checks HTTP response status.
  8. Build a form that sends JSON data to an API.
  9. Display loading, success, and error messages for all requests.
  10. Handle a 204 No Content response without trying to parse an empty body as JSON.
  11. Add a retry button for failed GET requests.
  12. Prevent users from submitting a form multiple times while it is processing.
  13. Test how the application behaves when the network is disconnected.
  14. Organize API logic in a separate service file.
  15. Build a small CRUD application that demonstrates all five HTTP methods.

22. Interview Questions and Answers

Q1. What is an HTTP request?

An HTTP request is a message sent by a client to a server to retrieve information or perform an operation on a resource.

Q2. What is the Fetch API?

The Fetch API is a JavaScript interface for sending network requests and receiving responses from servers.

Q3. What is the purpose of GET?

GET is commonly used to retrieve a resource or collection of resources from a server.

Q4. What is the purpose of POST?

POST submits data to a server and is commonly used to create a resource or initiate an operation.

Q5. What is the purpose of PUT?

PUT commonly replaces the representation of a specified resource with the data sent in the request.

Q6. What is the purpose of PATCH?

PATCH applies partial modifications to an existing resource, according to the API's supported patch format.

Q7. What is the purpose of DELETE?

DELETE requests removal of a specified resource.

Q8. What is the difference between PUT and PATCH?

PUT commonly replaces a resource representation, while PATCH commonly changes selected fields. Their precise behavior depends on the backend contract.

Q9. What is JSON.stringify() used for?

It converts a JavaScript value, usually an object, into a JSON string suitable for a JSON request body.

Q10. What is the Content-Type header?

It identifies the media type of the request body, such as application/json.

Q11. What does response.json() do?

It reads the response body and parses it as JSON, returning a Promise that resolves to the parsed value.

Q12. What does response.ok indicate?

It indicates whether the HTTP status code is in the successful 200–299 range.

Q13. Does Fetch reject a Promise for a 404 response?

Not normally. The Promise generally resolves to a Response object, so the application should check the status explicitly.

Q14. What is a REST API?

A REST API exposes resources through endpoints and uses HTTP methods to communicate the intended operations.

Q15. What is an API endpoint?

An API endpoint is a URL through which an application accesses a particular resource or server operation.

Q16. What is the difference between a network error and an HTTP error?

A network error occurs when the request cannot complete at the network or transport level. An HTTP error is a response from the server with an unsuccessful status code.

Q17. Why use async/await?

Async/await makes Promise-based code easier to read and allows asynchronous steps to be written in a sequential style.

Q18. Why use try/catch with Fetch?

It provides a place to handle rejected requests and errors thrown while processing the response.

Q19. What is a 204 No Content response?

It indicates that the request succeeded but the server is not returning a response body. The application should not automatically try to parse it as JSON.

Q20. What is AbortController?

AbortController can provide an AbortSignal to cancel a supported Fetch request when it is no longer needed.

Q21. How can API data be displayed in React Native?

Store the returned data in React state and render it using components such as Text, View, and FlatList.

Q22. Why use a reusable API service?

It reduces duplicated request code and centralizes shared settings, response checks, and error handling.

Q23. What is CRUD?

CRUD stands for Create, Read, Update, and Delete. These operations are commonly implemented with POST, GET, PUT or PATCH, and DELETE.

Q24. Why should an application handle loading states?

Network requests take time. Loading feedback helps users understand that an operation is in progress and reduces uncertainty.

Q25. How can duplicate POST requests be prevented?

Disable repeated submissions while the first request is running, and use backend-supported idempotency mechanisms when appropriate.

Q26. Why is HTTPS important?

HTTPS encrypts data in transit and helps protect requests and responses against interception and tampering.

Q27. Can a DELETE request have a body?

Some APIs define a DELETE body, but many do not require one. Follow the API's contract and client/runtime support.

Q28. What is the difference between local state and server data?

Local state is the information currently stored in the application's runtime. Server data is managed by the backend and may be shared across users or devices. The UI should be synchronized with server results according to the application's design.

Q29. What is pagination?

Pagination retrieves a large collection in smaller sets, reducing the amount of data transferred and processed at once.

Q30. How should API errors be displayed to users?

Show clear and helpful messages, preserve relevant form data where appropriate, and offer retry options when safe. Avoid exposing credentials or internal server details.

23. Quick Revision Checklist

  • Understand the purpose of HTTP requests and API endpoints.
  • Know the differences between GET, POST, PUT, PATCH, and DELETE.
  • Use Fetch with async/await and try/catch.
  • Set the correct HTTP method and headers.
  • Use JSON.stringify() when sending JSON request bodies.
  • Check response.ok and response.status.
  • Parse response bodies according to their actual format.
  • Handle 204 No Content responses correctly.
  • Manage loading, success, empty, and error states.
  • Update local state after successful write operations.
  • Use cancellation or stale-response protection where appropriate.
  • Keep credentials secure and use HTTPS.
  • Test both successful and unsuccessful API scenarios.
  • Organize repeated request logic into reusable service functions.

24. Conclusion

GET, POST, PUT, PATCH, and DELETE are essential HTTP methods for building data-driven React Native applications. GET retrieves information, POST submits data or creates resources, PUT commonly replaces a resource, PATCH commonly applies partial changes, and DELETE requests resource removal.

Reliable API integration requires more than sending a request. Developers must also configure headers and request bodies correctly, check HTTP status codes, parse responses appropriately, handle errors, manage loading states, and update the interface after server operations.

Practice each method using a testing API before integrating a real backend. For production applications, follow the backend documentation, use HTTPS, protect authentication credentials, and test network failures and unexpected responses.

25. Additional Learning Resources

whatsapp