ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalEC-332Webapi Crud Example
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    EC-332

    Enterprise Application Development

    Progress0 / 37 done
    Topics37
    1Microsoft technology history2Introduction to .NET and its architecture3Concept of MSIL, CLR, CLS, CTS
    4Managed and Unmanaged Code5.Net Assembly6Introduction to C# fundamentals7Boxing and Unboxing8Implementing multi-tier architecture
    9SQL Injection, parameterized queries10Usage of data set, Data adapter and command builder in disconnected model
    11Multicast delegates12Introduction to windows forms13HTML
    14javascript and its data types, variables, functions15Debugging javascript using Firebug
    16Browser's Object (BOM), Document Object Model
    17Jquery effects
    18LINQ to Objects, LINQ to SQL19Query syntax, Operations (projection, filtering and join) using Linq Queries
    20The entity data model, CSDL21Eager vs lazy loading, POCO classes, DBContext API22Querying entity data models23Introduction to ASP.NET MVC24MVC application structure, Controllers overview25Action Methods, Parameterized action methods26Introduction to razor syntax27Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28Data annotations, Client and Server Side Validation29Validation and model binding, Validation and model state30MVC Membership, Authorization and security
    31SOAP, WSDL32Service contract, Data contract, XML, WCF bindings33ABC of WCF, Restful services34Consuming rest services (CRUD operations) using Jquery AJAX and JSON35Introduction to web API36Example of web API using CRUD Example37MVC routing
    6 min read
    Topic 36 of 37
    Topic Study Note Illustration
    36

    Example of web API using CRUD Example

    Let's build a simple Web API using Node.js and Express to manage a collection of books . The API will allow users to perform CRUD (Create, Read,...

    Example of Web API Using CRUD Operations

    Let's build a simple Web API using Node.js and Express to manage a collection of books. The API will allow users to perform CRUD (Create, Read, Update, Delete) operations on books.

    We'll assume that the data for books is stored in memory (as an array) for simplicity. In a real-world application, this data would likely be stored in a database.

    Steps:

    1. Install Node.js and Express:

      • First, you need to have Node.js installed. If you haven't installed it yet, download and install it from nodejs.org.
      • Next, create a new directory for your project and initialize a new Node.js project:
        mkdir books-api
        cd books-api
        npm init -y
        
    2. Install Express:

      • Install the Express library, which simplifies handling HTTP requests:
        npm install express
        
    3. Create the API:

      • Create a file called app.js (or any name you prefer) to define your API.

    The Code (app.js):

    const express = require('express');
    const app = express();
    
    // Middleware to parse JSON bodies
    app.use(express.json());
    
    // In-memory book data
    let books = [
        { id: 1, title: '1984', author: 'George Orwell', year: 1949 },
        { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 }
    ];
    
    // 1. CREATE: Add a new book
    app.post('/api/books', (req, res) => {
        const { title, author, year } = req.body;
        
        if (!title || !author || !year) {
            return res.status(400).json({ message: 'Title, author, and year are required' });
        }
    
        const newBook = {
            id: books.length + 1, // Generate a new ID
            title,
            author,
            year
        };
    
        books.push(newBook);
        res.status(201).json(newBook);
    });
    
    // 2. READ: Get all books
    app.get('/api/books', (req, res) => {
        res.json(books);
    });
    
    // 3. READ: Get a single book by ID
    app.get('/api/books/:id', (req, res) => {
        const bookId = parseInt(req.params.id);
        const book = books.find(b => b.id === bookId);
    
        if (!book) {
            return res.status(404).json({ message: 'Book not found' });
        }
    
        res.json(book);
    });
    
    // 4. UPDATE: Update a book by ID
    app.put('/api/books/:id', (req, res) => {
        const bookId = parseInt(req.params.id);
        const { title, author, year } = req.body;
    
        const bookIndex = books.findIndex(b => b.id === bookId);
        if (bookIndex === -1) {
            return res.status(404).json({ message: 'Book not found' });
        }
    
        const updatedBook = {
            id: bookId,
            title: title || books[bookIndex].title,
            author: author || books[bookIndex].author,
            year: year || books[bookIndex].year
        };
    
        books[bookIndex] = updatedBook;
        res.json(updatedBook);
    });
    
    // 5. DELETE: Delete a book by ID
    app.delete('/api/books/:id', (req, res) => {
        const bookId = parseInt(req.params.id);
        const bookIndex = books.findIndex(b => b.id === bookId);
    
        if (bookIndex === -1) {
            return res.status(404).json({ message: 'Book not found' });
        }
    
        books.splice(bookIndex, 1); // Remove the book from the array
        res.status(204).send(); // No content in the response body
    });
    
    // Start the server
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
    

    Explanation of CRUD Operations:

    1. Create (POST):

      • The POST /api/books endpoint is used to create a new book.
      • The data for the book (title, author, year) is sent in the body of the request as JSON.
      • If successful, it adds a new book to the in-memory array and returns the newly created book as the response.

      Example request:

      POST http://localhost:3000/api/books
      Content-Type: application/json
      
      {
          "title": "Brave New World",
          "author": "Aldous Huxley",
          "year": 1932
      }
      
    2. Read (GET):

      • The GET /api/books endpoint retrieves all books.
      • The GET /api/books/:id endpoint retrieves a single book by its id.
      • The server returns the list of books or a single book in JSON format.

      Example request:

      GET http://localhost:3000/api/books
      

      Example response:

      [
          { "id": 1, "title": "1984", "author": "George Orwell", "year": 1949 },
          { "id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960 }
      ]
      

      Example request for a single book:

      GET http://localhost:3000/api/books/1
      

      Example response:

      { "id": 1, "title": "1984", "author": "George Orwell", "year": 1949 }
      
    3. Update (PUT):

      • The PUT /api/books/:id endpoint updates an existing book.
      • It accepts the updated data (title, author, year) in the request body.
      • If the book is found by its ID, it is updated with the new data, and the updated book is returned in the response.

      Example request:

      PUT http://localhost:3000/api/books/1
      Content-Type: application/json
      
      {
          "title": "Nineteen Eighty-Four",
          "author": "George Orwell",
          "year": 1949
      }
      

      Example response:

      { "id": 1, "title": "Nineteen Eighty-Four", "author": "George Orwell", "year": 1949 }
      
    4. Delete (DELETE):

      • The DELETE /api/books/:id endpoint deletes a book by its id.
      • If the book is found, it is removed from the array, and a 204 No Content status is returned, indicating that the operation was successful but there is no response body.

      Example request:

      DELETE http://localhost:3000/api/books/1
      

      Example response:

      Status: 204 No Content
      

    Testing the Web API with Postman or cURL:

    You can test the API using Postman (a popular tool for API testing) or cURL (command-line tool for transferring data).

    For example, to test the Create operation using cURL:

    curl -X POST http://localhost:3000/api/books \
    -H "Content-Type: application/json" \
    -d '{"title": "Brave New World", "author": "Aldous Huxley", "year": 1932}'
    

    To test the Read operation (getting all books):

    curl http://localhost:3000/api/books
    

    Conclusion:

    This simple Node.js + Express Web API example demonstrates how to create CRUD operations to manage resources (in this case, books). The API supports creating, reading, updating, and deleting books, and it returns responses in JSON format, which is the standard for most modern web APIs. This pattern can be expanded to include features like authentication, validation, and database integration.

    ← Previous topic 35
    Introduction to web API
    Next topic 37 →
    MVC routing

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    6mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Enterprise Application Development