Skip to content

API implementation

uswah-batool edited this page Apr 13, 2025 · 15 revisions

Important information for Deadline 3

‼️  This chapter should be completed by Deadline 3 (see course information at Lovelace)


📑  Chapter summary In this section you must implement a RESTful API. The minimum requirements are summarized in the Minimum Requirements section of the Project Work Assignment. If you do not meet the minimum requirements this section WILL NOT be evaluated.

CHAPTER GOALS

  • Implement a RESTful API
  • Write tests for the API

✔️     Chapter evaluation (max 21 points) You can get a maximum of 21 points after completing this section. More detailed evaluation is provided in the evaluation sheet in Lovelace.

RESTful API implementation

List of implemented resources

📑  Content that must be included in the section A list of all resourcess. Each resource should include its URL, a short description and supported methods. You should mark also which is the name of the class implementing the resource (if you have implemented such resource) Consider that you do not need to implement every resource you initially planned.   The minimum requirements are summarized in the Minimum requirements section from the Project work assignment.

✏️ List your resources here. You can use the table below for listing resources. You can also list unimplemented resources if you think they are worth mentioning

Resource Name Resource URL Description Supported Methods Implemented
Users /users Manage users GET, POST Yes
Single User /users/<uuid:user_id> Manage specific user GET, PUT, DELETE Yes
Task Collection /tasks Manage tasks GET, POST Yes
Single Task /tasks/<uuid:task_id> Manage individual task GET, PUT, DELETE Yes
Project Collection /projects Manage projects GET, POST Yes
Single Project /projects/<uuid:project_id> Manage specific project GET, PUT, DELETE Yes
Team Collection /teams Manage teams GET, POST Yes
Single Team /teams/<uuid:team_id> Manage individual team GET, PUT, DELETE Yes
Team Memberships /teams/<uuid:team_id>/members Add and retrieve members of a team POST, GET Yes
Team Memberships /teams/<uuid:team_id>/members/<uuid:user_id> Update and delete members of a team PUT, DELETE Yes


Basic implementation

💻     TODO: SOFTWARE TO DELIVER IN THIS SECTION The code repository must contain:
  1. The source code for the RESTful API 
  2. The external libraries that you have used
  3. We recommend to include a set of scripts to setup and run your server
  4. A database file or the necessary files and scripts to automatically populate your database.
  5. A README.md file containing:
    • Dependencies (external libraries)
    • How to setup the framework.
    • How to populate and setup the database.
    • How to setup (e.g. modifying any configuration files) and run your RESTful API.
    • The URL to access your API (usually nameofapplication/api/version/)=> the path to your application.
Do not forget to include in the README.md file which is the path to access to your application remotely.

NOTE: Your code MUST be clearly documented. For each public method/function you must provide: a short description of the method, input parameters, output parameters, exceptions (when the application can fail and how to handle such fail).  In addition should be clear which is the code you have implemented yourself and which is the code that you have borrowed from other sources. Always provide a link to the original source. This includes links to the course material.


✏️ You do not need to write anything in this section, just complete the implementation.


RESTful API testing

💻     TODO: SOFTWARE TO DELIVER IN THIS SECTION The code repository must contain:
  1. The code to test your RESTful API (Functional test)
    • The code of the test MUST be commented indicating what you are going to test in each test case.
    • The test must include values that force error messages
  2. The external libraries that you have used
  3. We recommend to include a set of scripts to execute your tests.
  4. A database file or the necessary files and scripts to automatically populate your database.
  5. A README.md file containing:
    • Dependencies (external libraries)
    • Instructions on how to run the different tests for your application.
Do not forget to include in the README.md the instructions on how to run your tests. Discuss briefly which were the main errors that you detected thanks to the functional testing.

Remember that you MUST implement a functional testing suite. A detailed description of the input / output in the a REST client plugin.

In this section it is your responsibility that your API handles requests correctly. All of the supported methods for each resource should work. You also need to show that invalid requests are properly handled, and that the response codes are correct in each situation.


✏️ Most important part of this section is completing the implementation. Write down here a short reflection on which are the main errors you have solved thanks to the functional tests.


REST conformance

📑  Content that must be included in the section Explain briefly how your API meets REST principles. Focus specially in these three principles: Addressability, Uniform interface, Statelessness. Provide examples (e.g. how does each HTTP method work in your API). Note that Connectedness will be addressed in more depth in Deadline 4.

Addressability

Our API follows the Addressability principle by ensuring that each resource has a unique and well-defined URI. For example

  • /users is dedicated to users resources
  • /tasks is dedicated to tasks resources
  • /projects is dedicated to projects resources
  • /teams is dedicated to teams resources

This structure allows clients to easily interact with specific entities.

Uniform Interface

We maintain a Uniform Interface by providing a standardized way to interact with resources using HTTP methods:

  • POST: Used to create new resources (e.g., POST /users, POST /tasks).
  • GET: Retrieves existing resources (e.g., GET /tasks, GET /users/uuid:user_id).
  • PUT: Updates an existing resource (e.g., PUT /tasks/uuid:task_id).
  • DELETE: Removes a resource (e.g., DELETE /teams/uuid:team_id, DELETE /projects/uuid:project_id).

Additionally, our API follows best practices:

  • Resource-Based URIs: Each URI represents a resource rather than an action
    Example: /tasks/<uuid:task_id> instead of /updateTask

  • Consistent HTTP Status Codes:

    • 200 OK - Successful operations
    • 201 Created - A new resource was successfully created
    • 400 Bad Request - Invalid inputs
    • 404 Not Found - Resource does not exist

Statelessness

Our API is stateless, meaning each request contains all the necessary information for processing. This is achieved by:

  • No Server-Side Sessions:
    The server does not store client session data; instead, each request includes authentication details.

  • Client-Managed State:
    Clients handle authentication using JWT tokens, which are sent with each request for verification.

  • Scalability & Simplicity:
    Since no session data is stored, the API remains scalable and efficient, allowing multiple servers to handle requests without dependency on previous interactions.

This design ensures a reliable, consistent, and scalable RESTful API.


Extras

📑  Details on extra features This section lists the additional features that will be graded as part of the API but are not required. In addition to implementing the feature you are also asked to write a short description for each.

URL Converters

📑  Fill this section if you used URL converters Write a short rationale of how URL converters are used, including your thoughts on the possible trade-offs. Go through all URL parameters in your API and describe whether they use a converter, what property is used for converting, or why it's not using a converter.

In our application, URL converters are used for specific parameters in the route definitions to ensure proper data types are passed and handled correctly. For example,

  • team_id: The team_id parameter is specified as uuid:team_id in the route definition, meaning Flask will automatically convert the value from the URL into a UUID object.
  • user_id: Similarly, the user_id parameter is specified as uuid:user_id, and Flask will convert the string from the URL into a UUID object.

URL converters are useful for automatically converting URL parameters into the appropriate data types. In the above case, using the uuid converter ensures that the team_id and user_id parameters are always treated as UUID objects. This reduces the need for manual type conversion in the route functions and ensures that invalid formats are caught before reaching the code logic.


Schema Validation

📑  Fill this section if you used JSON schema validation Write a short description of your JSON schemas, including key decision making for choosing how to validate each field.

Schema validation is used in our application to ensure that incoming data matches the expected format before it is processed. Specifically, the validate_json decorator is applied to certain routes, ensuring that the incoming request data conforms to predefined JSON schemas. For example,

  • create_team: The TEAM_SCHEMA is used to validate the request body before creating a new team.
  • update_team: The TEAM_SCHEMA is used again to validate the data when updating a team.
  • add_team_member: The TEAM_MEMBERSHIP_SCHEMA is used to validate the request body before adding a new team member.

Using schema validation ensures that incoming data is structured correctly and meets the expected requirements.


Caching

📑  Fill this section if you implemented server side caching Explain your caching decisions here. Include an explanation for every GET method in your API, explaining what is cached (or why it is not cached), and how long is it cached (and why). If you are using manual cache clearing, also explain when it happens.

Caching is used in our application to store the results of specific routes for a set period of time. This helps reduce the load on the server by avoiding repeated database queries for the same data within a short time. For example,

  • GET /teams/uuid:team_id: This endpoint uses the @cache.cached(timeout=60) decorator to cache the response for 60 seconds.
  • GET /teams/uuid:team_id/members: This endpoint also uses the same caching strategy with a 60-second cache timeout.

Caching improves performance by reducing redundant database queries and speeding up response times for frequently accessed data.


Authentication

📑  Fill this section if you implemented authentication Explain your authentication scheme here. Describe the authentication requirements for each resource in your API, and your reasoning for the decisions. In addition, provide a plan for how API keys will be distributed, even if the distribution is not currently implemented.

Authentication is used in our application. The @jwt_required() decorator is applied to multiple routes. This ensured that only users with a valid JWT (JSON Web Token) can access those endpoints. The JWT is checked for each request to verify the user's identity.

JWTs allow the server to authenticate requests without needing to store session data. Each request is self-contained, with the user's identity embedded in the token.


Use of AI


📝 We used ChatGPT to enhance sentence structure and readability of the documentation.


Resource Allocation

Task Student Estimated Time
Implementation (Authentication, Caching, Team Routes, User Routes, Schemas, Schema Validation, Model Modifications) Muhammad Hassan Sohail 6 hours
Tests (Configuration Tests, Authentication Tests, User Route Tests, Task Route Modification Tests) Syed Abdullah Hassan 4 hours
Routes (Task Route) + Tests (Task Route Tests) Matheo 2 hours
Code Review and Fixes + Documentation Uswah Batool 4 hours
Fixes from deliverable 2 Student Estimated time
Worked on on_delete behavior for all foreign keys Matheo 2 hours