___________________________
Initiated December 8th, 2023.
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.
- If any bugs are discovered, please contact the author.
- Visual Studio Code
- C#
- ASP.NET Core
- MySQL 8.0.34
- Entity Framework Core 6.0.0
- Entity Framework Core CLI Tools 6.0.0
- Entity Framework Core Identity 6.0.0
- JWT Bearer
- Swagger - NSwag 13.3.0
- Postman
- Docker
- 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.
In Terminal for macOS or PowerShell for Windows, enter the following command to install the REPL dotnet-script:
$ dotnet tool install -g dotnet-script
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
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.
(Optional) Download and install Postman.
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.
- Code Editor Download:
- Click the download most applicable to your OS and system.
- Wait for download to complete, then install -- Windows will run the setup exe and macOS will drag and drop into applications.
- Optionally, create a GitHub Account
- Navigate to the Cranberry API repository here.
- Click 'Clone or download' to reveal the HTTPS url ending with .git and the 'Download ZIP' option.
- Open up your system Terminal or GitBash, navigate to your desktop with the command:
cd Desktop
, or whichever location suits you best. - Clone the repository to your desktop:
$ git clone https://github.com/jfpalchak/CranberryAPI.git
- Run the command
cd CranberryAPI/CranberryAPI
to enter into the project directory. - 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.
- Code Editor - Run the command
- Navigate to the Cranberry API repository here.
- Click 'Clone or download' to reveal the HTTPS url ending with .git and the 'Download ZIP' option.
- Click 'Download ZIP' and extract.
- Open by double clicking on any of the files to open in a text editor.
- Create a new file in the CranberryAPI project directory named
appsettings.json
- 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]"
}
}
- 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). - In order to properly implement JSON Web Tokens for API authorization, replace
[YOUR-SECRET-HERE]
with your own personalized string.- 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.
- NOTE: The
- Navigate to CranberryAPI/CranberryAPI directory using the MacOS Terminal or Windows Powershell (e.g.
cd Desktop/CranberryAPI/CranberryAPI
). - Run the command
dotnet ef database update
to generate the database through Entity Framework Core. - (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 commanddotnet ef database update
to update the database.
- Navigate to CranberryAPI/CranberryAPI directory using the MacOS Terminal or Windows Powershell (e.g.
cd Desktop/CranberryAPI/CranberryAPI
). - Run the command
dotnet watch run
to have access to the API in Postman or browser.
Explore the API endpoints in Postman or a browser. However, take note: you will not be able to utilize authentication in a browser.
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
In order to be authorized to use the GET
, POST
, PUT
, and DELETE
functionality of the API, please authenticate yourself through Postman:
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!"
}
http://localhost:5000/api/users/register
{
"status": "Success",
"message": "User has been successfully created."
}
Here's an example of what this should look like 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:
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!"
}
http://localhost:5000/api/users/signin
{
"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:
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:
Until the Token expires, you should now have access to all endpoints requiring user authorization!
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.
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} |
..........................................................................................
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.
..........................................................................................
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.
Parameter | Type | Default | Required | Description |
---|---|---|---|---|
No parameters. |
https://localhost:5001/api/users/1
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
}
}
..........................................................................................
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.
Parameter | Type | Default | Required | Description |
---|---|---|---|---|
id | int | none | true | Specify the desired user according to the given User ID. |
https://localhost:5001/api/users/profile
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
}
}
..........................................................................................
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.
Parameter | Type | Default | Required | Description |
---|---|---|---|---|
id | int | none | true | Specify the desired user according to the given User ID. |
https://localhost:5001/api/users/1
{
"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.
Status: 204 No Content
..........................................................................................
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.
Parameter | Type | Default | Required | Description |
---|---|---|---|---|
id | int | none | true | Specify the desired user according to the given User ID. |
https://localhost:5001/api/users/1
Status: 204 No Content
..........................................................................................
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.
Parameter | Type | Default | Required | Description |
---|---|---|---|---|
id | int | none | true | Specify the desired user according to the given User ID. |
https://localhost:5001/api/users/1/journals
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"
}
]
}
..........................................................................................
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.
Parameter | Type | Default | Required | Description |
---|---|---|---|---|
id | int | none | true | Specify the desired user according to the given User ID. |
https://localhost:5001/api/users/1/journals/
{
"date": "2023-12-13",
"cravingIntensity": 0,
"cigsSmoked": 5,
"notes": "Some test notes.",
}
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"
}
}
..........................................................................................
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.
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. |
https://localhost:5001/api/users/1/journals/64
{
"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.
Status: 204 No Content
..........................................................................................
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.
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. |
https://localhost:5001/api/users/1/journals/52
Status: 204 No Content
..........................................................................................
Access functionality to read from a list of health benefits one might achieve over a period of time after they have quit smoking.
..........................................................................................
If you have any feedback or concerns, please contact one of the contributors.
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