{"id":7991,"date":"2024-11-13T04:32:10","date_gmt":"2024-11-13T04:32:10","guid":{"rendered":"https:\/\/studysection.com\/blog\/?p=7991"},"modified":"2024-11-13T06:08:02","modified_gmt":"2024-11-13T06:08:02","slug":"simplifying-serialization-in-fastapi-with-example","status":"publish","type":"post","link":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/","title":{"rendered":"Simplifying Serialization in FastAPI with Example"},"content":{"rendered":"<p>When we talk about web development, especially with APIs, we often come across the term &#8220;serialization.&#8221; But what does it mean in simple terms? Serialization is the process of converting complex data types (like Python objects) into a format that can be easily shared and stored (like JSON). This is crucial for <a href=\"https:\/\/studysection.com\/blog\/api-testing-and-its-types\/\">APIs<\/a> because it allows us to send and receive data over the internet in a format that both the server and client understand.<\/p>\n<p>FastAPI, a modern and fast web framework for building APIs with Python, makes serialization straightforward and efficient, thanks to Pydantic models. These models help in both serialization (Python objects to JSON) and deserialization (JSON to Python objects), ensuring that the data exchanged is valid.<\/p>\n<p><strong>Example: A Book API with FastAPI and Pydantic<\/strong><br \/>\nLet&#8217;s create a simple book API that demonstrates serialization in FastAPI. Our goal is to define a book model, create an endpoint to add a new book, and another to retrieve all the books.<\/p>\n<p><strong>Step 1: Setting up the FastAPI Project<\/strong><br \/>\nFirst, ensure you have FastAPI and Uvicorn (an ASGI server) installed. If not, you can install them using pip:<\/p>\n<p><code>pip install fastapi uvicorn<\/code><\/p>\n<p><strong>Step 2: Defining the Book Model with Pydantic<\/strong><br \/>\nCreate a file named main.py and start by defining a Pydantic model for our book. This model will automatically handle serialization and validation for us.<\/p>\n<p><code>from typing import List<br \/>\nfrom fastapi import FastAPI<br \/>\nfrom pydantic import BaseModel<\/code><\/p>\n<p><code>class Book(BaseModel):<br \/>\ntitle: str<br \/>\nauthor: str<br \/>\nyear: int<\/code><\/p>\n<p><code>app = FastAPI()<br \/>\n# A simple in-memory storage to store books<br \/>\nbooks: List[Book] = []<\/code><\/p>\n<p><strong>Step 3: Creating an Endpoint to Add a New Book<\/strong><br \/>\nNow, let&#8217;s create an endpoint where we can send a POST request to add a new book. FastAPI makes it super simple to define the request body using Pydantic models.<\/p>\n<p><code>@app.post(\"\/books\/\")<br \/>\nasync def add_book(book: Book):<br \/>\nbooks.append(book)<br \/>\nreturn {\"message\": \"Book added successfully!\"}<\/code><\/p>\n<p><strong>Step 4: Creating an Endpoint to Retrieve All Books<\/strong><br \/>\nNext, we need an endpoint to get all the books we&#8217;ve added. Since our books list already contains Book objects, FastAPI will automatically serialize them into JSON when we return them in the response.<\/p>\n<p><code>@app.get(\"\/books\/\")<br \/>\nasync def get_books():<br \/>\nreturn books<\/code><\/p>\n<p><strong>Step 5: Running the API<\/strong><br \/>\nFinally, run your FastAPI application using Uvicorn:<\/p>\n<p><code>uvicorn main:app --reload<\/code><\/p>\n<p>Now, you can use a tool like Postman or cURL to test adding and retrieving books. For example, to add a book, you would send a POST request to http:\/\/localhost:8000\/books\/ with a JSON body like:<br \/>\n<code>{<br \/>\n\"title\": \"The Great Gatsby\",<br \/>\n\"author\": \"F. Scott Fitzgerald\",<br \/>\n\"year\": 1925<br \/>\n}<\/code><\/p>\n<p>To retrieve all books, simply send a GET request to http:\/\/localhost:8000\/books\/.<\/p>\n<p>Serialization in FastAPI, powered by Pydantic, is a breeze. By defining our data models, FastAPI and Pydantic take care of the heavy lifting, allowing us to easily send and receive structured data over the web. This simplifies creating robust and scalable APIs, letting developers focus on building features rather than worrying about data conversion and validation.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>When we talk about web development, especially with APIs, we often come across the term &#8220;serialization.&#8221; But what does it<\/p>\n","protected":false},"author":1,"featured_media":7992,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Simplifying Serialization in FastAPI with Example<\/title>\n<meta name=\"description\" content=\"When we talk about web development, especially with APIs, we often come across the term &quot;serialization. what does it mean in simple terms?\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Simplifying Serialization in FastAPI with Example\" \/>\n<meta property=\"og:description\" content=\"When we talk about web development, especially with APIs, we often come across the term &quot;serialization. what does it mean in simple terms?\" \/>\n<meta property=\"og:url\" content=\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog Posts on famous people, innovations and educational topics\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/studysection\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-13T04:32:10+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-13T06:08:02+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2024\/11\/Add-a-subheading-16.png\" \/>\n\t<meta property=\"og:image:width\" content=\"940\" \/>\n\t<meta property=\"og:image:height\" content=\"788\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"admin-studysection-blog\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@studysection\" \/>\n<meta name=\"twitter:site\" content=\"@studysection\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin-studysection-blog\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/\"},\"author\":{\"name\":\"admin-studysection-blog\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\"},\"headline\":\"Simplifying Serialization in FastAPI with Example\",\"datePublished\":\"2024-11-13T04:32:10+00:00\",\"dateModified\":\"2024-11-13T06:08:02+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/\"},\"wordCount\":423,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"articleSection\":[\"Learn and Grow\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/\",\"url\":\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/\",\"name\":\"Simplifying Serialization in FastAPI with Example\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/#website\"},\"datePublished\":\"2024-11-13T04:32:10+00:00\",\"dateModified\":\"2024-11-13T06:08:02+00:00\",\"description\":\"When we talk about web development, especially with APIs, we often come across the term \\\"serialization. what does it mean in simple terms?\",\"breadcrumb\":{\"@id\":\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/studysection.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Simplifying Serialization in FastAPI with Example\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/studysection.com\/blog\/#website\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"name\":\"Blog Posts on famous people, innovations and educational topics\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/studysection.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/studysection.com\/blog\/#organization\",\"name\":\"StudySection\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"contentUrl\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"width\":920,\"height\":440,\"caption\":\"StudySection\"},\"image\":{\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/studysection\",\"https:\/\/twitter.com\/studysection\",\"https:\/\/www.instagram.com\/study.section\/\",\"https:\/\/www.linkedin.com\/company\/studysection\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\",\"name\":\"admin-studysection-blog\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"caption\":\"admin-studysection-blog\"},\"url\":\"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Simplifying Serialization in FastAPI with Example","description":"When we talk about web development, especially with APIs, we often come across the term \"serialization. what does it mean in simple terms?","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/","og_locale":"en_US","og_type":"article","og_title":"Simplifying Serialization in FastAPI with Example","og_description":"When we talk about web development, especially with APIs, we often come across the term \"serialization. what does it mean in simple terms?","og_url":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/","og_site_name":"Blog Posts on famous people, innovations and educational topics","article_publisher":"https:\/\/www.facebook.com\/studysection","article_published_time":"2024-11-13T04:32:10+00:00","article_modified_time":"2024-11-13T06:08:02+00:00","og_image":[{"width":940,"height":788,"url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2024\/11\/Add-a-subheading-16.png","type":"image\/png"}],"author":"admin-studysection-blog","twitter_card":"summary_large_image","twitter_creator":"@studysection","twitter_site":"@studysection","twitter_misc":{"Written by":"admin-studysection-blog","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/#article","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/"},"author":{"name":"admin-studysection-blog","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402"},"headline":"Simplifying Serialization in FastAPI with Example","datePublished":"2024-11-13T04:32:10+00:00","dateModified":"2024-11-13T06:08:02+00:00","mainEntityOfPage":{"@id":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/"},"wordCount":423,"commentCount":0,"publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"articleSection":["Learn and Grow"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/","url":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/","name":"Simplifying Serialization in FastAPI with Example","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/#website"},"datePublished":"2024-11-13T04:32:10+00:00","dateModified":"2024-11-13T06:08:02+00:00","description":"When we talk about web development, especially with APIs, we often come across the term \"serialization. what does it mean in simple terms?","breadcrumb":{"@id":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/studysection.com\/blog\/simplifying-serialization-in-fastapi-with-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/studysection.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Simplifying Serialization in FastAPI with Example"}]},{"@type":"WebSite","@id":"https:\/\/studysection.com\/blog\/#website","url":"https:\/\/studysection.com\/blog\/","name":"Blog Posts on famous people, innovations and educational topics","description":"","publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/studysection.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/studysection.com\/blog\/#organization","name":"StudySection","url":"https:\/\/studysection.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","contentUrl":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","width":920,"height":440,"caption":"StudySection"},"image":{"@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/studysection","https:\/\/twitter.com\/studysection","https:\/\/www.instagram.com\/study.section\/","https:\/\/www.linkedin.com\/company\/studysection"]},{"@type":"Person","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402","name":"admin-studysection-blog","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","caption":"admin-studysection-blog"},"url":"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/"}]}},"views":253,"_links":{"self":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/7991"}],"collection":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/comments?post=7991"}],"version-history":[{"count":3,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/7991\/revisions"}],"predecessor-version":[{"id":7995,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/7991\/revisions\/7995"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media\/7992"}],"wp:attachment":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media?parent=7991"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/categories?post=7991"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/tags?post=7991"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}