πŸ“‘ AngularJS HTTP & Services
Estimated reading: 4 minutes 27 views

πŸ“¬ AngularJS HTTP Methods: GET, POST, PUT, DELETE, JSONP – Complete API Integration Guide (2025)

🧲 Introduction – Why Learn AngularJS HTTP Methods?

Most AngularJS applications rely on external data sources or APIs. Whether you’re fetching a list of products, submitting a form, updating a user profile, or deleting a record, the $http service gives you full control over these HTTP methods: GET, POST, PUT, DELETE, and JSONP.

Understanding these methods helps you:

  • Build dynamic and data-driven SPAs
  • Perform CRUD operations on backend data
  • Handle API responses and errors properly

🎯 In this guide, you’ll learn:

  • The syntax and use cases of each HTTP method in AngularJS
  • Real-world examples using $http
  • How to handle JSONP for cross-domain requests
  • Tips for headers, configuration, and best practices

βš™οΈ Overview of HTTP Methods

MethodPurposeUse Case Example
GETRetrieve dataFetch user list
POSTSend new data to the serverCreate a new user
PUTUpdate existing dataEdit user profile
DELETERemove data from the serverDelete a blog post
JSONPCross-domain GET using script tagsFetch public data from an API

βœ… 1. GET – Retrieve Data

Use GET to read data from an API or server.

$http.get("https://api.example.com/users")
  .then(function(response) {
    $scope.users = response.data;
  })
  .catch(function(error) {
    console.error("GET Error:", error);
  });

βœ… Use When: Displaying lists, tables, reports, charts, etc.


βœ… 2. POST – Send Data

Use POST to submit data, such as forms or new records.

$http.post("https://api.example.com/users", {
  name: "Alice",
  email: "alice@example.com"
})
.then(function(response) {
  $scope.message = "User created successfully!";
})
.catch(function(error) {
  $scope.error = "Failed to create user.";
});

βœ… Use When: Creating new entries, form submissions.


βœ… 3. PUT – Update Data

Use PUT to replace or update existing records.

$http.put("https://api.example.com/users/101", {
  name: "Alice Smith",
  email: "alice@newdomain.com"
})
.then(function(response) {
  $scope.message = "User updated.";
})
.catch(function(error) {
  console.error("Update failed:", error);
});

βœ… Use When: Updating profile info, settings, or any existing record.


βœ… 4. DELETE – Remove Data

Use DELETE to remove a resource identified by a unique ID or endpoint.

$http.delete("https://api.example.com/users/101")
  .then(function(response) {
    $scope.message = "User deleted.";
  })
  .catch(function(error) {
    console.error("Delete error:", error);
  });

βœ… Use When: Removing items, cancelling accounts, deleting posts.


βœ… 5. JSONP – Cross-Domain Data Fetching

JSONP (JSON with Padding) is used to overcome cross-origin restrictions when a server does not support CORS.

$http.jsonp("https://api.publicapis.org/entries?callback=JSON_CALLBACK")
  .then(function(response) {
    $scope.apis = response.data.entries;
  });

βœ… JSONP requests must include ?callback=JSON_CALLBACK.


πŸ§ͺ Using $http with Config Objects

For better control, use $http() with custom config:

$http({
  method: 'POST',
  url: 'https://api.example.com/products',
  data: { name: "Phone", price: 999 },
  headers: { 'Content-Type': 'application/json' }
})
.then(function(res) {
  console.log("Product added:", res.data);
});

πŸ” Adding Custom Headers

Useful for authentication or content negotiation:

$http.get("/api/secure-data", {
  headers: {
    'Authorization': 'Bearer ' + token
  }
});

🧠 Real-World Examples

ScenarioHTTP MethodDescription
Show all usersGETLoad user list in dashboard
Register new accountPOSTSubmit sign-up form
Update user profilePUTEdit existing user info
Delete contact from address bookDELETERemove data from server
Fetch COVID stats from public APIJSONPAccess cross-origin JSON data

πŸ› οΈ Best Practices

βœ”οΈ Always use .catch() for error handling
βœ”οΈ Prefer POST for form submissions, not GET
βœ”οΈ Use JSONP only when CORS is unavailable
βœ”οΈ Structure API logic in services, not controllers
βœ”οΈ Secure requests with authentication headers if required


πŸ“Œ Summary – Recap & Next Steps

AngularJS supports all common HTTP methods out of the box through its $http service, making it easy to build rich, data-driven applications that interact with remote servers.

πŸ” Key Takeaways:

  • Use GET to fetch data, POST to create, PUT to update, and DELETE to remove
  • Use JSONP for cross-origin requests if CORS is unsupported
  • Always manage promises using .then() and .catch()
  • Prefer services for reusable HTTP calls

βš™οΈ Real-world Relevance:
These methods are used in dashboards, admin panels, CRMs, eCommerce apps, real-time reporting tools, and data entry systems.


❓ FAQ – AngularJS HTTP Methods


❓ What’s the difference between POST and PUT in AngularJS?
βœ… POST is used to create a new resource. PUT is used to update an existing one.


❓ Can I send custom headers with AngularJS HTTP requests?
βœ… Yes. Use the headers property inside your $http() config.


❓ When should I use JSONP in AngularJS?
βœ… Use JSONP only when calling external APIs that do not support CORS. Ensure the server supports JSONP format.


❓ Are these HTTP methods asynchronous?
βœ… Yes. All $http calls are asynchronous and return a promise.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ“¬ AngularJS HTTP Methods: GET, POST, PUT, DELETE, JSONP

Or Copy Link

CONTENTS
Scroll to Top