Zero Labs
Industry News / AI

FastAPI CRUD Tutorial: Build Your First REST API with Python

Source · Towards AI By Sameer Chauhan

From the publisher’s feed, collected in the ZeroLabs newsroom.

Build a solid foundation in backend development by creating clean, scalable APIs with FastAPI — step by step, from basics to real-world CRUD implementation.IntroFastAPI is one of the fastest-growing Python framework for building APIs . It’s known for its high performance, automatic documentation, and simple syntax based on python type hints.In this article, we will build simple a CRUD API that manages AI enterprises like OpenAI, Google and Anthropic. Along the way, we will be learning the core HTTP request methods used in REST APIs.In this tutorial you will learn:How to install FastAPIHow to run a FastAPI serverHow to build CRUD endpointsHow to use path parametersHow to use query parametersHow to test APIs with Swagger UIProject SetupFirst, create a new Python file called.main.py# Install the required dependenciespip install fastapi uvicorn'''FastAPI -> API framework Uvicorn -> ASGI server used to run the API'''#Run the server with uvicorn main:app --reload#Open your browser and visithttp://127.0.0.1:8000/docs'''You will see the automatic Swagger API documentation generated by FastAPI'''Creating Sample DataFor this tutorial, we will create a list of enterprises that will act as our temporary database.# Now let's import FastAPI and create our application instance from fastapi import Body, FastAPIapp = FastAPI() # creating an app instance Enterprises = [{ "id": 1,"company": "OpenAI", "CEO": "Sam Altman", "model": "ChatGPT" },{ "id": 2,"company": "Google", "CEO": "Sundar Pichai", "model": "Gemini" },{ "id": 3,"company": "Anthropic", "CEO": "Sam Altman", "model": "Claude" },{ "id": 4,"company": "X", "CEO": "Elon Musk", "model": "Grok" },{ "id": 5,"company": "Preplixity", "CEO": "Aravind Srinivas", "model": "Preplexity" },]'''Each enterprise contains:- id - comapny - CEO - AI model'''HTTP Request Methods in CRUDThese HTTP methods allow clients to interact with server data.| CRUD operation | HTTP methods ||-------------------------------|| Create | POST || Read | GET || Update | PUT || Delete | DELETE ||-------------------------------|GET Request — Reading DataThe GET request method is used to read data from the server without making any changes to it.# Get Endpoint@app.get("/")def root(): return Enterprises # return the list of enterprisesGET endpointPath ParametersPath parameters are variables that are part of the URL path itself. They allow you to capture values directly from the URL.'''example URL: https://127.0.0.1:8000/enterprises/OpenAIFrom the URL, we have:-> Base URL: https://jsonplaceholder.typicode.com-> Path: /enterprises/{company}-> Path parameter value: OpenAI'''@app.get("/enterprises/{company}")# we declare path parameters using curly {}, which makes that part of the path dynamicdef read_company(company: str): # here "str" is type hint ( convert the parameter to specified type, Validate the value before calling the funtion) for enterprise in Enterprises: if enterprise.["company"].casefold() == company.casefold(): # casefold() is similar to the lower() method, but stronger and more aggressive return enterprise# This endpoint searches for an enterprise by its company name.Query ParametersQuery parameters are request parameters in the URL after a question mark(?). Multiple are separated by an ampersand(&).'''Example:-> http://127.0.0.1:8000/enterprises/?model=ChatGPTThe query parameter here is:-> model → ChatGPT'''@app.get("/enterprises/")def read_by_model(model: str): result = [] for entrprise in Enterprises: if enterprise["model"].casefold() == model.casefold(): result.append(enterprise) return result# This endpoint returns enterprises based on their AI model.Path parameterPost Request — Creating DataThe POST method is used to create data to the server.Post request has an additional area to be able to send data called the body. You can send data in the body that can be used by FastAPI.# POST Endpoint@app.post("/enterprises/create")def create_enterprise(new_enterprise=Body()): Enterprises.append(new_enterprise) return {"message": "Enterprise added"}POST endpointPUT Request — Updating DataThe PUT request method is used to update data. PUT can have a body that has additional information'''Example of a Body:{ "id": 1,"company": "OpenAI", "CEO": "Sam Altman", "model": "ChatGPT" }we can update company, CEO, model we can't change the id as it's giving uniqueness to each JSON'''# PUT Endpoint@app.put("/enterprises/update")def update_enterprise(updated_enterprise=Body()): for i in range(len(Enterprises)): if Enterprises[i]["id"] == updated_enterprise.get["id"]: Enterprises[i] = updated_enterprise return {"message": "Enterprise updated"}# This endpoint finds an enterprise by id and replaces it with the updated data.PUT endpointDELETE Request — Removing the DataThe DELETE request method is used to delete data. In the same manner as PUT request, we will delete a enterprise list by searching with “id”.'''The request URL could be: -> http://127.0.0.1:8000/enterprises/delete/{id}'''#DELETE Endpoint@app.delete("/enterprisis/delete/{id}")def delete_enterprise(id: int): for i in range(len(Enterprises)): if Enterprises[i]["id"] == id: Enterprises.pop(i) return {"message": "Enterprise deleted"}DELETE endpointFastAPI automatically generates interactive API documentation.Open:http://127.0.0.1:8000/docsHere you can :Test all endpointsSend request bodiesview API responsesKey TakeawaysFastAPI makes API development simple and fast.CRUD operations map directly to HTTP methods.FastAPI automatically generates documentation.Python type hints improve validation and developer experience.ConclusionIn this tutorial we built a CRUD API using FastAPI and explored how HTTP methods work in RESTful services.FastAPI’s simplicity and performance make it an execllebt choice for modern backend development.Add a Call-to-ActionIf you enjoyed this tutorial, follow me on Medium for more Python and backend development guides.FastAPI CRUD Tutorial: Build Your First REST API with Python was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.