Adrian David
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Food Alerts API Python Wrapper The FSA Food Alerts API provides data on alerts regarding food safety and hygiene, ranging from undeclared allergens to pathogen risks. The dataset the API provides has tremendous potential for data analysis which can provide interesting insights about the food market. However, accessing data from the API and parsing the results can be tricky- requiring multiple calls for nested data, nested for loops to access properties and the like. The first phase of my internship project aims to solve this. I created a Python wrapper for the FSA Food Alerts API with the ultimate aim of making the API easier to discover and use. The wrapper makes accessing and processing data from the API very simple by abstracting away the details of HTTP requests and response parsing. This leaves the user with the freedom to analyse and process this data with the aid of getter functions (which works well with code completion aids, such as IntelliSense) and convenience functions. To help users get started, I have created usage examples that demonstrate how easily the wrapper can be used to access and process data from the API. These demos will be the main focus of this blog post. Documentation is also available [here](https://food-alerts-wrapper.readthedocs.io/en/latest/) which provides more information about the classes and functions in the package. ## Usage Examples ### Plotting the 10 most common allergens in the past year *** ![Allergens column chart](https://i.imgur.com/tOEvUEB.png) def plotTopAllergens(f): yearAgo = (datetime.now() - timedelta(days=365)).isoformat() alerts = f.getAlerts(yearAgo) allergenCounts = defaultdict(int) alert: Alert # type hinting for code completion for alert in alerts: allergens = alert.allergenLabels() for allergen in allergens: allergenCounts[allergen] += 1 # get the 10 most frequently occurring allergens sortedAllergens = [ (k, v) for k, v in sorted( allergenCounts.items(), key=lambda item: item[1], reverse=True )][:10] labels = [k for (k, v) in sortedAllergens] heights = [v for k, v in sortedAllergens] plt.bar(labels, heights, color="green") plt.xticks(rotation="vertical") plt.title("10 Most Common Allergens in the Past Year") plt.tight_layout() plt.show() <br> As you can see above, the abstraction provided by the wrapper allows for concise and readable code. The entirety of data acquisition and parsing has been done using only the wrapper methods `getAlerts()` and `allergenLabels()`. Accessing data from the API using the wrapper is as simple as calling the `getAlerts()` method. The Alert objects' attributes are then easily accessible using their getter methods. We opted to use getter methods instead of accessing the attributes directly to exploit code completion aids. There is a catch however: since Python is dynamically typed, *type hinting has to be used* to tell Python that a variable is an Alert object. An example is shown below. ![IntelliSense and type hinting](https://i.imgur.com/yR7nABY.png) `allergenLabels()` makes accessing the allergens in an alert more convenient. Accessing this attribute otherwise would be tedious due to the complex data structure of Alert objects. ### Plotting the alert counts per month in 2019 *** ![Alert count per month in 2019](https://i.imgur.com/DRt5TZr.png) def plotAlertCountPerMonth(f): # get alerts from 1 January 2019 lastYear = date(2019, 1, 1).isoformat() alerts = f.getAlerts(lastYear) monthlyCount = defaultdict(int) # filter alerts to those created in 2019 # and tally results alert: Alert # type hinting for code completion for alert in alerts: yearCreated = date.fromisoformat(alert.created()).year monthCreated = date.fromisoformat(alert.created()).month if (yearCreated == 2019): monthlyCount[monthCreated] += 1 xAxis = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] yAxis = [monthlyCount[i] for i in range(1, 13)] # configuring and displaying plot plt.plot(xAxis, yAxis) plt.title("Alert count per month in 2019") plt.xticks(rotation=45) plt.tight_layout() plt.show() Above is another example of data visualisation using the wrapper. The same approach applies: using `getAlerts()` to access data, and then obtaining useful information from the data using getter methods, in this case `created()`. So far, we have only used `getAlerts()` to obtain alerts since a given date by providing a date string in ISO format. We can also provide an integer, `n`, as a parameter instead to get `n` alerts from the API. For example, `getAlerts(5)` would return 5 alerts. Note, however, that the API is non-deterministic and subsequent calls to it can return different results (even without any updates to the API database). To get deterministic results, some criteria for sorting has to be specified. To get the `n` most recent alerts for example, a `sortBy` parameter has to be provided: `getAlerts(5, sortBy='-created')`. This returns 5 alerts from the API, sorted by the `created` attribute in descending (latest first, hence the minus sign) order. `getAlerts()` can take more optional parameters such as filters and offsets for pagination, details of which are available in the [documentation](). The wrapper also provides more methods for obtaining data from the API, namely `searchAlerts()` and `getAlert()`. `searchAlerts()` takes as a required parameter a string to search the API database for. It then returns a list of alerts that match the query string. `getAlert()`, as the name suggests, returns only one alert. It takes as parameter an alert's `notation` attribute which uniquely identifies any given alert. `getAlert()` returns more details about a specific alert than `getAlerts()` does. ### Creating a front-end application with the API *** ![Frontend: Using the wrapper with Flask](https://i.imgur.com/LNnN6IX.png) ![Frontend: Using the wrapper with Flask (search)](https://i.imgur.com/UhARXav.png) ![Frontend: Using the wrapper with Flask (alert details)](https://i.imgur.com/uVeMAnP.png) from foodAlertsAPI import foodAlertsAPI f = foodAlertsAPI() @app.route('/', methods=["GET", "POST"]) def alerts(): query = request.form.get("query", "") if query == "": alerts = f.getAlerts(24) else: alerts = f.searchAlerts(query, limit=24) return render_template('index.html', alerts=alerts, query=query) @app.route('/alert/<id>') def alertDetails(id): alert = f.getAlert(id) allergens = alert.allergenLabels() pathogenRisks = alert.pathogenRiskLabels() return render_template('alert.html', alert=alert, allergens=allergens, pathogenRisks=pathogenRisks) <br> The code above shows the server side of a web application written in Flask (the front-end code is omitted for brevity). This example might be less interesting from a data analysis standpoint, but it serves to show how `searchAlerts()` and `getAlert()` can be used. f

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully