ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Enterprise Application Development
    EC-332
    Progress0 / 37 topics
    Topics
    1. Overview of Enterprise Application Development: Microsoft technology history2. Introduction to .NET and its architecture3. Concept of MSIL, CLR, CLS, CTS4. Introduction to .NET framework: Managed and Unmanaged Code5. .Net Assembly6. Introduction to C# fundamentals7. Boxing and Unboxing8. Implementing multi-tier architecture9. Introduction to ADO.Net: SQL Injection, parameterized queries10. Usage of data set, Data adapter and command builder in disconnected model11. Introduction to delegate: Multicast delegates12. Introduction to windows forms13. HTML14. Introduction to javascript: javascript and its data types, variables, functions15. Debugging javascript using Firebug16. Introduction to various object models: Browser's Object (BOM), Document Object Model17. Introduction to Jquery: Jquery effects18. Introducing LINQ: LINQ to Objects, LINQ to SQL19. Query syntax, Operations (projection, filtering and join) using Linq Queries20. Introduction to ADO.NET entity framework: The entity data model, CSDL21. Eager vs lazy loading, POCO classes, DBContext API22. Querying entity data models23. Introduction to ASP.NET MVC24. MVC application structure, Controllers overview25. Action Methods, Parameterized action methods26. Introduction to razor syntax27. Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28. Data annotations, Client and Server Side Validation29. Validation and model binding, Validation and model state30. MVC Membership, Authorization and security31. Introduction to service-oriented architecture: SOAP, WSDL32. Service contract, Data contract, XML, WCF bindings33. ABC of WCF, Restful services34. Consuming rest services (CRUD operations) using Jquery AJAX and JSON35. Introduction to web API36. Example of web API using CRUD Example37. MVC routing
    EC-332›Example of web API using CRUD Example
    Enterprise Application DevelopmentTopic 36 of 37

    Example of web API using CRUD Example

    6 minread
    1,086words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,086
      Code examples0
      DifficultyIntermediate