Giter VIP home page Giter VIP logo

cranberryapi's Introduction


Cranberry API


external-cranberry-flavors-colored-outline-part-2-colored-outline-lafs

___________________________

by Joey Palchak

ย  ย 

Initiated December 8th, 2023.


Table of Contents


๐ŸŒ About the Project

๐Ÿ“– Description

The Cranberry API allows users to both register and sign in to their own account, as well as post, put, and delete their own Journal entries and account information. This API utilizes RESTful principles, as well as Json Web Tokens (JWT) for authentication & authorization.

Only authenticated users have access to GET, POST, PUT, and DELETE functionality throughout the API.

๐Ÿฆ  Known Bugs

  • If any bugs are discovered, please contact the author.

๐Ÿ›  Technology Used


๐Ÿ Getting Started

๐Ÿ“‹ Prerequisites

Install .NET Core

  • On macOS with Apple Chip:
    • Click here to download the .NET Core SDK from Microsoft Corp for macOS.
  • On macOs with Intel Chip:
    • Click here to download the .NET Core SDK from Microsoft Corp for macOS.
  • On Windows:
    • Click here to download the 64-bit .NET Core SDK from Microsoft Corp for Windows.

Install dotnet-script

In Terminal for macOS or PowerShell for Windows, enter the following command to install the REPL dotnet-script:

$ dotnet tool install -g dotnet-script

Install dotnet-ef

For Entity Framework Core, we'll use a tool called dotnet-ef to reference the project's migrations and update our database accordingly. To install this tool globally, run the following command in your terminal:

$ dotnet tool install --global dotnet-ef --version 6.0.0

Optionally, you can run the following command to verify that EF Core CLI tools are correctly installed:

$ dotnet ef

Install MySQL Workbench

This project assumes you have MySQL Server and MySQL Workbench installed on your system. If you do not have these tools installed, follow along with the installation steps for the the necessary tools introduced in the series of lessons found here on LearnHowToProgram.

Or, Download and install the appropriate version of MySQL Workbench.

Install Postman

(Optional) Download and install Postman.

Code Editor

To view or edit the code, you will need a code editor or text editor. A popular open-source choice for a code editor is VisualStudio Code.

  1. Code Editor Download:
  2. Click the download most applicable to your OS and system.
  3. Wait for download to complete, then install -- Windows will run the setup exe and macOS will drag and drop into applications.
  4. Optionally, create a GitHub Account

โš™๏ธ Setup and Use

Cloning

  1. Navigate to the Cranberry API repository here.
  2. Click 'Clone or download' to reveal the HTTPS url ending with .git and the 'Download ZIP' option.
  3. Open up your system Terminal or GitBash, navigate to your desktop with the command: cd Desktop, or whichever location suits you best.
  4. Clone the repository to your desktop: $ git clone https://github.com/jfpalchak/CranberryAPI.git
  5. Run the command cd CranberryAPI/CranberryAPI to enter into the project directory.
  6. View or Edit:
    • Code Editor - Run the command code . to open the project in VisualStudio Code for review and editing.
    • Text Editor - Open by double clicking on any of the files to open in a text editor.

Download

  1. Navigate to the Cranberry API repository here.
  2. Click 'Clone or download' to reveal the HTTPS url ending with .git and the 'Download ZIP' option.
  3. Click 'Download ZIP' and extract.
  4. Open by double clicking on any of the files to open in a text editor.

AppSettings

  1. Create a new file in the CranberryAPI project directory named appsettings.json
  2. Add in the following code snippet to the new appsettings.json file:
{
    "Logging": {
        "LogLevel": {
        "Default": "Warning"
        }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Port=3306;database=cranberry_api;uid=[YOUR-USERNAME-HERE];pwd=[YOUR-PASSWORD-HERE];"
    },
    "JWT": {
        "ValidAudience": "example-audience",
        "ValidIssuer": "example-issuer",
        "Secret": "[YOUR-SECRET-HERE]"
  }
}
  1. Change the server, port, and user id as necessary. Replace [YOUR-USERNAME-HERE] and [YOUR-PASSWORD-HERE] with your personal MySQL username and password (set at installation of MySQL).
  2. In order to properly implement JSON Web Tokens for API authorization, replace [YOUR-SECRET-HERE] with your own personalized string.
    1. NOTE: The Secret is a special string that will be used to encode our JWTs, to make them unique to our application. Depending on what type of algorithm being used, the Secret string will need to be a certain length. In this case, it needs to be at least 16 characters long.

Database

  1. Navigate to CranberryAPI/CranberryAPI directory using the MacOS Terminal or Windows Powershell (e.g. cd Desktop/CranberryAPI/CranberryAPI).
  2. Run the command dotnet ef database update to generate the database through Entity Framework Core.
  3. (Optional) To update the database with any changes to the code, run the command dotnet ef migrations add <MigrationsName> which will use Entity Framework Core's code-first principle to generate a database update. 4) After, run the previous command dotnet ef database update to update the database.

Launch the API

  1. Navigate to CranberryAPI/CranberryAPI directory using the MacOS Terminal or Windows Powershell (e.g. cd Desktop/CranberryAPI/CranberryAPI).
  2. Run the command dotnet watch run to have access to the API in Postman or browser.

๐Ÿ›ฐ๏ธ API Documentation

Explore the API endpoints in Postman or a browser. However, take note: you will not be able to utilize authentication in a browser.

Using Swagger Documentation

To explore the Cranberry API with NSwag, launch the project using dotnet run with the Terminal or Powershell, and input the following URL into your browser: http://localhost:5000/swagger

Registering an Account and Using the JSON Web Token

In order to be authorized to use the GET, POST, PUT, and DELETE functionality of the API, please authenticate yourself through Postman:

POST Register

Again, we'll be using Postman for this example. Let's setup a POST request to the users/register endpoint. Select the 'Body' tab, choose the 'raw' radio button, and select 'JSON' from the dropdown selection.

In the Body of the Post request, use the following format:

{
    "email": "[email protected]",
    "userName": "testUser",
    "password": "Password123!"
}

Example Query

http://localhost:5000/api/users/register

Sample JSON Response

{
    "status": "Success",
    "message": "User has been successfully created."
}

Here's an example of what this should look like in Postman:

Register endpoint in Postman

Note that the password must contain at least six characters, one non-alphanumeric character, at least one digit lowercase letter, at least one uppercase letter and at least two unique characters. An invalid password will generate the following response from the API:

Password-Req error in Postman

POST Sign In

Now that we've registered an account with our API, we'll need to authenticate our account and generate a JSON Web Token. We'll be using Postman again for this example.

Let's setup another POST request to the users/signin endpoint. Select the 'Body' tab, choose the 'raw' radio button, and select 'JSON' from the dropdown selection.

In the Body of the Post request, use the following format:

{
    "email": "[email protected]",
    "password": "Password123!"
}

Example Query

http://localhost:5000/api/users/signin

Sample JSON Response

{
    "status": "Success",
    "message": "[email protected] signed in.",
    "token": "xxxx.xxxx.xxxx",
    "userId": "xxx"
}

Here's an example of what this should look like in Postman:

Sign In endpoint in Postman

Using the JSON Web Token

Now let's copy that token from the response, and add it as an authorization header to our next request. Copy the token from the body, and click on the Authorization tab in Postman. On the 'Type', make sure that is set to 'Bearer Token', and then paste in the token in the field on the right.

Here's an example of what that should look like in Postman:

Using a JSON Web Token in Postman

Until the Token expires, you should now have access to all endpoints requiring user authorization!

Note on CORS

CORS is a W3C standard that allows a server to relax the same-origin policy. It is not a security feature, CORS relaxes security. It allows a server to explicitly allow some cross-origin requests while rejecting others. An API is not safer by allowing CORS. For more information or to see how CORS functions, see the Microsoft documentation.


API Endpoints

Base URL: https://localhost:5001

Users
POST /api/users/register
POST /api/users/signin
GET /api/users/profile
GET /api/users/{id}
PUT /api/users/{id}
DELETE /api/users/{id}
User Journals
GET /api/users/{id}/journals
POST /api/users/{id}/journals
PUT /api/users/{id}/journals/{id}
DELETE /api/users/{id}/journals/{id}

..........................................................................................

Users Controller

Access functionality to register, sign-in & receive a Token, as well as edit or delete your account. The Users controller also contains endpoints for Users to create, read, update, or delete their own Journal entries.

..........................................................................................

GET /api/users/profile

This is an alternative endpoint to GET /api/users/{id}

Authenticated users, while including their Token in the authorization header of the request, may access this GET endpoint. On a successful request, this endpoint returns the User's registered information.

NOTE: An authenticated user is only authorized to retrieve their own information, and upon successfully calling this endpoint, will receive only their own registered information.

Path Parameters

Parameter Type Default Required Description
No parameters.

Example Query

https://localhost:5001/api/users/1

Sample JSON Response

Status: 200 OK

{
    "status": "Success",
    "message": "User info retrieved successfully.",
    "data": {
        "userId": "1",
        "userName": "Joey",
        "quitDate": "2023-12-15T12:27",
        "avgSmokedDaily": 5,
        "pricePerPack": 11.55,
        "cigsPerPack": 20
    }
}

..........................................................................................

GET /api/users/{id}

This is an alternative endpoint to GET /api/users/profile

Authenticated users, while including their Token in the authorization header of the request, may access this GET endpoint. On a successful request, this endpoint returns the User's registered information.

NOTE: An authenticated user is only authorized to retrieve their own information. If an ID belonging to an account other than the authenticated user is used, regardless of a present bearer token, the request will receive a 404 response.

Path Parameters

Parameter Type Default Required Description
id int none true Specify the desired user according to the given User ID.

Example Query

https://localhost:5001/api/users/profile

Sample JSON Response

Status: 200 OK

{
    "status": "Success",
    "message": "User info retrieved successfully.",
    "data": {
        "userId": "1",
        "userName": "Joey",
        "quitDate": "2023-12-15T12:27",
        "avgSmokedDaily": 5,
        "pricePerPack": 11.55,
        "cigsPerPack": 20
    }
}

..........................................................................................

PUT /api/user/{id}

Authenticated users, while including their Token in the authorization header of the request, may access the PUT endpoint to update their registered information.

NOTE: An authenticated user is only authorized to access and update their own information.

Path Parameters

Parameter Type Default Required Description
id int none true Specify the desired user according to the given User ID.

Example Query

https://localhost:5001/api/users/1

Sample JSON Request Body

{
     "userId": "1",
     "userName": "Joey",
     "quitDate": "2023-12-15T12:27",
     "avgSmokedDaily": 10,
     "pricePerPack": 12,
     "cigsPerPack": 20
}

NOTE: When sending a PUT request, the User's ID is required in the body of the request.

Sample Successful JSON Response

Status: 204 No Content

..........................................................................................

DELETE /api/users/{id}

Authenticated users, while including their Token in the authorization header of the request, may DELETE their own registered account

NOTE: An authenticated user is only authorized to access and update their own information. Attempting to access this endpoint with a User ID that does not belong to the authenticated user will result in an unsuccessful request.

Path Parameters

Parameter Type Default Required Description
id int none true Specify the desired user according to the given User ID.

Example Query

https://localhost:5001/api/users/1

Sample Successful JSON Response

Status: 204 No Content

..........................................................................................

GET /api/users/{id}/journals

Authenticated users, while including their Token in the authorization header of the request, may access this GET endpoint. On a successful request, this endpoint returns a list of all the User's Journal submissions.

NOTE: An authenticated user is only authorized to access and update their own journals. Attempting to access this endpoint with a User ID that does not belong to the authenticated user will result in an unsuccessful request.

Path Parameters

Parameter Type Default Required Description
id int none true Specify the desired user according to the given User ID.

Example Query

https://localhost:5001/api/users/1/journals

Sample Successful JSON Response

Status: 200 OK

{
    "status": "Success",
    "message": "Journals retrieved successfully.",
    "data": [
        {
            "journalId": 52,
            "date": "2023-12-13T16:58",
            "cravingIntensity": 2,
            "cigsSmoked": 3,
            "notes": "Notes here.",
            "userId": "1"
        },
        {
            "journalId": 53,
            "date": "2023-12-04T16:58",
            "cravingIntensity": 3,
            "cigsSmoked": 5,
            "notes": "Some more notes.",
            "userId": "1"
        }
    ]
}

..........................................................................................

POST /api/users/{id}/journals/

Authenticated users, while including their Token in the authorization header of the request, may access this POST endpoint to create a new journal entry.

NOTE: An authenticated user is only authorized to access and update their own journals. Attempting to access this endpoint with a User ID that does not belong to the authenticated user will result in an unsuccessful request.

Path Parameters

Parameter Type Default Required Description
id int none true Specify the desired user according to the given User ID.

Example Query

https://localhost:5001/api/users/1/journals/

Sample JSON Request Body

{
   "date": "2023-12-13",
   "cravingIntensity": 0,
   "cigsSmoked": 5,
   "notes": "Some test notes.",
}

Sample Successful JSON Response

Status: 201 Created

{
    "status": "Success",
    "message": "Journal created successfully.",
    "data": {
        "journalId": 64,
        "date": "2023-12-13",
        "cravingIntensity": 0,
        "cigsSmoked": 5,
        "notes": "Something new.",
        "userId": "1"
    }
}

..........................................................................................

PUT /api/users/{id}/journals/{journalId}

Authenticated users, while including their Token in the authorization header of the request, may access this PUT endpoint to update a specific journal they have authored.

NOTE: An authenticated user is only authorized to access and update their own journals. Attempting to access this endpoint with a User ID that does not belong to the authenticated user will result in an unsuccessful request.

Path Parameters

Parameter Type Default Required Description
id int none true Specify the desired user according to the given User ID.
journalId int none true Specify the desired journal according to the given Journal ID.

Example Query

https://localhost:5001/api/users/1/journals/64

Sample JSON Request Body

{
   "journalId": 64,
   "date": "2023-12-13",
   "cravingIntensity": 10,
   "cigsSmoked": 5,
   "notes": "Some different notes.",
}

NOTE: When sending a PUT request, the Journal's ID is required in the body of the request.

Sample Successful JSON Response

Status: 204 No Content

..........................................................................................

DELETE /api/users/{id}/journals/{id}

Authenticated users, while including their Token in the authorization header of the request, may DELETE specific Journal entries in the database that they have authored.

NOTE: An authenticated user is only authorized to access and update their own journals. Attempting to access this endpoint with a User ID that does not belong to the authenticated user will result in an unsuccessful request.

Path Parameters

Parameter Type Default Required Description
id int none true Specify the desired user according to the given User ID.
journalId int none true Specify the desired journal according to the given Journal ID.

Example Query

https://localhost:5001/api/users/1/journals/52

Sample Successful JSON Response

Status: 204 No Content

..........................................................................................

TO DO:

Milestones Controller

Access functionality to read from a list of health benefits one might achieve over a period of time after they have quit smoking.

..........................................................................................


โœ‰๏ธ Contact and Support

If you have any feedback or concerns, please contact one of the contributors.

Report Bug ยท Request Feature


โš–๏ธ License

This project is licensed under the MIT License. Copyright (C) 2023 Joey Palchak. All Rights Reserved.

MIT License

Copyright (c) 2023 Joey Palchak.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Return to Top

cranberryapi's People

Contributors

jfpalchak avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.